Last active
November 10, 2019 04:22
-
-
Save ugwis/41e663ee4d841419f70cd08a6641e0fa to your computer and use it in GitHub Desktop.
Shell Web Server
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
#!/bin/zsh | |
rm -f fifo0; rm -f fifo1; rm -f debug | |
function routine() { | |
while true | |
do | |
# Parse Request | |
http_method="";http_path="";http_version="";http_header=""; http_body=""; | |
target="http_request_line" | |
while read line | |
do | |
line=`echo $line | tr -d '\r' | tr -d '\n'` | |
echo $line > debug | |
if [[ "$target" == "http_request_line" ]];then | |
http_method=`echo $line | cut -d' ' -f1` | |
http_path=`echo $line | cut -d' ' -f2` | |
http_version=`echo $line | cut -d' ' -f3` | |
[[ $http_version =~ '^HTTP' ]] && target="http_header" | |
elif [[ "$target" == "http_header" ]];then | |
if [[ "$line" == "" ]];then | |
target="http_body" | |
echo -n "\r\n\r\n" > fifo0 | |
fi | |
http_header="$http_header$line" | |
elif [[ "$target" == "http_body" ]];then | |
[[ "$line" == "" ]] && break | |
http_body="$http_body$line" | |
fi | |
done | |
# Make Response Body | |
response_body=$http_body | |
# Respond HTTP | |
echo -n "$http_version 200 OK\r\n" | |
echo -n "Date: `date -u "+%Y-%m-%d %H:%M:%S GMT"`\r\n" | |
echo -n "Content-Length: $((${#response_body}+4))\r\n" | |
echo -n "\r\n" | |
echo -n $response_body | |
echo -n "\r\n" | |
echo -n "\r\n" | |
done | |
} | |
mkfifo fifo0 fifo1 debug | |
exec 3<> fifo0;exec 4<> fifo1;exec 5<> debug | |
cat debug& | |
nc -lk 8080 > fifo0 < fifo1 & | |
nc_pid=$! | |
trap " | |
echo \"shutting...\" >&2 | |
exec 3<&-;exec 4<&-;exec 5<&- | |
kill $nc_pid | |
rm -f fifo0;rm -f fifo1;rm -f debug | |
exit 1 | |
" 2 | |
echo "Listening 8080 ($nc_pid)" | |
routine < fifo0 > fifo1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment