Skip to content

Instantly share code, notes, and snippets.

@morten-olsen
Last active June 30, 2020 22:19
Show Gist options
  • Save morten-olsen/13e8d5df91a056b64de9d7d53cb18b34 to your computer and use it in GitHub Desktop.
Save morten-olsen/13e8d5df91a056b64de9d7d53cb18b34 to your computer and use it in GitHub Desktop.
Static HTTP server written in bash(-ish)
LOCATION="$1"
RES=/tmp/webreq
[ ! -p $RES ] && mkfifo $RES
function get_docment {
LOCATION=$(realpath .$(realpath "/$1"))
[ -d "$LOCATION" ] && echo "$LOCATION/index.html" || echo "$LOCATION"
}
function SEND {
cat >$RES <<EOF
HTTP/1.0 200 OK
Cache-Control: private
Content-Type: $(file -b --mimetype "$1")
Server: bash-http-server
Connection: Close
$(cat $1)
EOF
}
function NOT_FOUND {
cat >$RES <<EOF
HTTP/1.0 404 Not Found
Cache-Control: private
Server: bash-http-server
Connection: Close
Not found
EOF
}
while true; do
cat $RES | ncat -l 4444 | (
REQ=$(while read I && [ " " "<" "$I" ]; do echo "$I"; done)
FILE=.$(echo $REQ | head -1 | cut -d " " -f 2)
DOCUMENT=$(get_docment $FILE)
echo "Requesting $DOCUMENT"
[ -f "$DOCUMENT" ] && SEND "$DOCUMENT" || NOT_FOUND
)
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment