diff options
author | dan <[email protected]> | 2023-05-28 16:02:50 -0400 |
---|---|---|
committer | dan <[email protected]> | 2023-05-28 16:02:50 -0400 |
commit | 354616cc3536d7f0c58795373192f6b1e5a1cb0b (patch) | |
tree | b4c7b71463b81ccbe458999f28a7a184f81a8ffb | |
parent | 30affd41b3de4c2a7f90c21acb8a0ee8f3540223 (diff) | |
download | dump-354616cc3536d7f0c58795373192f6b1e5a1cb0b.tar.gz dump-354616cc3536d7f0c58795373192f6b1e5a1cb0b.tar.bz2 dump-354616cc3536d7f0c58795373192f6b1e5a1cb0b.zip |
feat: shell script http server
-rw-r--r-- | http-server.sh | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/http-server.sh b/http-server.sh new file mode 100644 index 0000000..aa5e17e --- /dev/null +++ b/http-server.sh @@ -0,0 +1,40 @@ +#!/bin/sh + +# Simple HTTP Server using Netcat (nc) +# +# Sends a greeting message and the date in the response. + + +# Info: Relies on the OpenBSD version of Netcat +# GNU netcat may or may not work. + +# Creating a FIFO so that the output of nc can be processed and used to determine the input. +# Allows for "passing values back round" +outfifo="/tmp/outfifo" +rm -f "$outfifo" +mkfifo "$outfifo" + +# Run forever +while true; do + x="$(date)" + len="$(echo "$x" | wc -c)" + cat "$outfifo" \ + | nc -l localhost 1500 \ + | while read -r line; do + line=$(echo "$line" | tr -d '\r\n') + echo "< $line" + + if echo "$line" | grep -qE '^GET /'; then + # on reading the request line, extract a value from the request path and build the response + name="$(echo $line | sed 's:GET /\([^ ]*\).*:\1:')" + content="Hello $name, the date and time is $(date)." + # Without Content-Length header, connection will not close properly + len="$(echo "$content" | wc -c)" + + response="HTTP/1.1 200 OK\nContent-Length: $len\nContent-Type: plain/text\n\n$content" + elif [ -z "$line" ]; then # end of request + # send response once all of the request has been read + echo -e "$response" > "$outfifo" + fi + done + done |