Skip to content

Instantly share code, notes, and snippets.

@dagrons
Forked from spelcaster/one-shot-server.service
Last active October 6, 2021 06:20
Show Gist options
  • Save dagrons/0eab4fa06741a73b8b2a83e1fc3c283a to your computer and use it in GitHub Desktop.
Save dagrons/0eab4fa06741a73b8b2a83e1fc3c283a to your computer and use it in GitHub Desktop.
Use netcat to serve a file through HTTP template
[Unit]
Description=One shot server using netcat
After=network.target
[Service]
Type=simple
PIDFile=/run/one_shot_server.pid
Restart=on-failure
Environment="PORT=4000"
Environment="FILE=/tmp/somefile.json"
ExecStart=/usr/bin/nohup /usr/local/bin/one_shot_server ${FILE} 0<&- &>/dev/null &
[Install]
WantedBy=multi-user.target
#/bin/bash
PID_FILE=/run/one_shot_server.pid
echo $$ > ${PID_FILE}
sighandler() {
echo "Caught signal!"
rm ${PID_FILE}
exit 0
}
trap sighandler HUP INT TERM
PORT=${PORT-8080}
FILE=${1}
if [[ -z "$FILE" ]]
then
echo "The file \"${FILE}\" does not exist"
exit 1
fi
while [[ 1 ]]
do
{ echo -ne "HTTP/1.0 200 OK\r\nContent-Length: $(wc -c <${FILE})\r\n\r\n"; cat ${FILE}; } | nc -l -p ${PORT}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment