-
-
Save antikytheraton/bc034517db8825009705bd50ec2fcc12 to your computer and use it in GitHub Desktop.
One-liner REST server using netcat - nc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rm -f out | |
mkfifo out | |
trap "rm -f out" EXIT | |
while true | |
do | |
cat out | nc -w1 -l 1500 > >( # parse the netcat output, to build the answer redirected to the pipe "out". | |
export REQUEST= | |
while read line | |
do | |
line=$(echo "$line" | tr -d '[\r\n]') | |
if echo "$line" | grep -qE '^GET /' # if line starts with "GET /" | |
then | |
REQUEST=$(echo "$line" | cut -d ' ' -f2) # extract the request | |
elif [ "x$line" = x ] # empty line / end of request | |
then | |
HTTP_200="HTTP/1.1 200 OK" | |
HTTP_LOCATION="Location:" | |
HTTP_404="HTTP/1.1 404 Not Found" | |
# call a script here | |
# Note: REQUEST is exported, so the script can parse it (to answer 200/403/404 status code + content) | |
if echo $REQUEST | grep -qE '^/echo/' | |
then | |
printf "%s\n%s %s\n\n%s\n" "$HTTP_200" "$HTTP_LOCATION" $REQUEST ${REQUEST#"/echo/"} > out | |
elif echo $REQUEST | grep -qE '^/date' | |
then | |
date > out | |
elif echo $REQUEST | grep -qE '^/stats' | |
then | |
vmstat -S M > out | |
elif echo $REQUEST | grep -qE '^/net' | |
then | |
ifconfig > out | |
else | |
printf "%s\n%s %s\n\n%s\n" "$HTTP_404" "$HTTP_LOCATION" $REQUEST "Resource $REQUEST NOT FOUND!" > out | |
fi | |
fi | |
done | |
) | |
done |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rm -f out ; mkfifo out ; trap "rm -f out" EXIT ; while true ; do cat out | nc -w1 -l 1500 > >(export REQUEST= ; while read line ; do line=$(echo "$line" | tr -d '[\r\n]') ; if echo "$line" | grep -qE '^GET /' ; then REQUEST=$(echo "$line" | cut -d ' ' -f2) ; elif [ "x$line" = x ] ; then HTTP_200="HTTP/1.1 200 OK" ; HTTP_LOCATION="Location:" ; HTTP_404="HTTP/1.1 404 Not Found" ; if echo $REQUEST | grep -qE '^/echo/' ; then printf "%s\n%s %s\n\n%s\n" "$HTTP_200" "$HTTP_LOCATION" $REQUEST ${REQUEST#"/echo/"} > out ; elif echo $REQUEST | grep -qE '^/date' ; then date > out ; elif echo $REQUEST | grep -qE '^/stats' ; then vmstat -S M > out ; elif echo $REQUEST | grep -qE '^/net' ; then ifconfig > out ; else printf "%s\n%s %s\n\n%s\n" "$HTTP_404" "$HTTP_LOCATION" $REQUEST "Resource $REQUEST NOT FOUND!" > out ; fi ; fi ; done) ; done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment