Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Created November 10, 2013 14:43
Show Gist options
  • Save coderofsalvation/7399049 to your computer and use it in GitHub Desktop.
Save coderofsalvation/7399049 to your computer and use it in GitHub Desktop.
bashweb is simple but powerfull bashscript which can start an generalpurpose httpserver. Its applications can be restful services, or simple html applications which can be ran locally in the browser.
#!/bin/bash
TMPFILE="/tmp/.bashweb.$(whoami)"
PORT=8080
start(){
[[ -n "$1" ]] && PORT="$1"; TMPFILE="$TMPFILE.$PORT"; [[ ! -p $TMPFILE ]] && mkfifo "$TMPFILE"
while [[ -p "$TMPFILE" ]]; do
[[ -f "$TMPFILE.log" ]] && tail -n5 $TMPFILE.log
{ read line<$TMPFILE;
logmsg(){ cat - | while read l; do echo "[$(date)] $1> $l" >> $TMPFILE.log; [[ ! "$1" == "in" ]] && echo "$l"; done
message="$( echo "$line" | sed 's/[\n\r]//g')"
method="$(echo "$message" | sed 's/ \/.*//g' )"
url="$(echo "$message" | sed 's/GET //g;s/POST //g;s/DELETE //g;s/PUT //g;s/ HTTP.*//g')"
echo "$method $url" | logmsg in
echo -e "HTTP/1.1 200 OK\r\n" | logmsg out
$0 onUrl "$method" "$url" "$TMPFILE"
} | nc -v -l $PORT > $TMPFILE | tee -a $TMPFILE.log
done
}
onUrl(){
method="$1"; url="$2"; tmpfile="$3"
case $url in
/REST) echo '{"code":0, "message": "'$(date)'" }'
;;
*) echo "<html><body><pre>$(tail -n15 "$3.log")</pre></body></html>"
;;
esac
}
cleanup(){
[[ -f "$TMPFILE" ]] && rm "$TMPFILE"
echo "server stopped"
exit
}
trap cleanup SIGINT
"$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment