summaryrefslogtreecommitdiffstats
path: root/http-server.sh
blob: 46633c77c6ee33e0657f6c79b63bc437a95c1ac9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/bin/sh

# Simple HTTP Server using Netcat (nc)
#
# Sends a greeting message and the date in the response.


# Warning: 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
    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="${#content}"

                response="HTTP/1.1 200 OK\nContent-Length: $len\n\n$content"
            elif [ -z "$line" ]; then # end of request
                # send response once all of the request has been read
                printf "%b" "$response" > "$outfifo"
            fi
        done
    done