Created
September 30, 2011 20:33
-
-
Save mumrah/1254898 to your computer and use it in GitHub Desktop.
Incomplete HTTP server in Awk
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires Gawk