Skip to content

Instantly share code, notes, and snippets.

@spelcaster
Last active June 7, 2021 01:45
Show Gist options
  • Save spelcaster/e54c40a593a1a909a26a179e9f1fde59 to your computer and use it in GitHub Desktop.
Save spelcaster/e54c40a593a1a909a26a179e9f1fde59 to your computer and use it in GitHub Desktop.
Use netcat to serve a file through HTTP
[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