Skip to content

Instantly share code, notes, and snippets.

@mumrah
Created September 30, 2011 20:33
Show Gist options
  • Save mumrah/1254898 to your computer and use it in GitHub Desktop.
Save mumrah/1254898 to your computer and use it in GitHub Desktop.
Incomplete HTTP server in Awk
BEGIN {
RS = ORS = "\r\n"
HttpService = "/inet/tcp/8000/0/0"
while(1) {
_NR = 0
while((HttpService |& getline) > 0) {
_NR += 1
handle_header($0)
}
close(HttpService)
}
}
function handle_header(line) {
if(_NR == 1) {
split(line, toks, " ");
METHOD = toks[1]
PATH = toks[2]
delete HEADERS
}
if(line == "") {
# Done receiving request
switch(METHOD) {
case "GET": resp = handle_GET(PATH, HEADERS);
}
send_resp(resp)
}
else {
split(line, toks, ": ");
HEADERS[toks[1]] = toks[2]
}
}
function handle_GET(path, headers){
Hello = "<HTML><HEAD>" \
"<TITLE>A Famous Greeting</TITLE></HEAD>" \
"<BODY><H1>Hello, world</H1></BODY></HTML>"
printLog("GET request for " path)
return Hello
}
function send_resp(Resp, Headers) {
Len = length(Resp) + length(ORS)
print "HTTP/1.0 200 OK" |& HttpService
print "Content-Length: " Len ORS |& HttpService
print Resp |& HttpService
}
function printLog(s){
SwapORS = ORS
ORS = "\n"
print s
ORS = SwapORS
}
@mumrah
Copy link
Author

mumrah commented Oct 11, 2011

Requires Gawk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment