Created
April 20, 2014 23:09
-
-
Save jnthn/11127634 to your computer and use it in GitHub Desktop.
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
class ACrappyAsyncHTTPServer { | |
has $.host; | |
has $.port; | |
has $.log; | |
has %!handlers; | |
method BUILD(:$!host, :$!port) { | |
$!log = Supply.new; | |
IO::Socket::Async.listen($!host, $!port).tap(-> $connection { | |
self!read_request($connection); | |
}); | |
} | |
method on($path, &what) { | |
%!handlers{$path}= &what; | |
} | |
method !read_request($connection) { | |
# Only cares for the headers. 'cus it's crappy, of course. :-) | |
my $req = ''; | |
my $tap := $connection.chars_supply.tap( | |
{ | |
$req ~= $_; | |
if $req.index("\r\n\r\n") -> $header_end { | |
self!process_request($connection, $req.substr(0, $header_end)); | |
} | |
}); | |
} | |
method !process_request($connection, $headers) { | |
my @lines = $headers.lines; | |
$!log.more(@lines[0]); | |
my @pieces = @lines[0].words; | |
if %!handlers{@pieces[1]} -> &handler { | |
self!respond($connection, '200 OK', handler()); | |
CATCH { | |
default { | |
self!respond($connection, '500 Internal Server Error', | |
"<h1>OMG Internal Server Error, man!</h1>"); | |
} | |
} | |
} | |
else { | |
self!respond($connection, '404 Not Found', | |
"<h1>Oh noes, I canny find it, like!</h1>"); | |
} | |
} | |
method !respond($connection, $status, $body) { | |
$connection.send( | |
"HTTP/1.1 $status\r\nContent-type: text/html\r\n\r\n$body" | |
).then({ | |
$connection.close(); | |
}); | |
} | |
} | |
my $server = ACrappyAsyncHTTPServer.new(host => '127.0.0.1', port => 4242); | |
$server.on('/', { "<h1>OMG TOASTER!</h1>" }); | |
$server.on('/1999', { "<marquee>Party like it's 1999</marquee>" }); | |
.say for $server.log.list; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment