Skip to content

Instantly share code, notes, and snippets.

@p120ph37
Last active July 15, 2020 00:38
Show Gist options
  • Save p120ph37/c0a6bd7579cb87446eeb to your computer and use it in GitHub Desktop.
Save p120ph37/c0a6bd7579cb87446eeb to your computer and use it in GitHub Desktop.
A better one-line webserver in Perl
socket$_,2,1,6;setsockopt$_,1,2,pack"l",1;(bind$_,pack"snN3",2,pop)||die$!;listen$_,128;{accept+my($c),$_;fork&&redo;($_)=<$c>=~/(\/\S*)/;s/%([0-9a-f]{2})/pack"H2",$1/eig;s-/$-/index.html-;!/\.\./&&open$a,"<.$_"||last;syswrite$c,"HTTP/1.1 200\x0D\x0A\x0D\x0A";syswrite$c,$,until!sysread$a,$,,1024}
@p120ph37
Copy link
Author

p120ph37 commented Oct 14, 2014

A saner variation on https://gist.github.com/p120ph37/49bf890ee37087d37114 that avoids directory traversal, serves "index.html" when a directory is requested, handles SO_REUSEADDR properly, reports errors when binding, forks in order to serve resources in parallel, streams from disk rather than slurping files entirely into memory, accepts a port number on the command line, and passes "strict" and "warnings" checks.

Run like this:
perl -e'...' 8080

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