Skip to content

Instantly share code, notes, and snippets.

@jnthn
Created April 20, 2014 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnthn/11127634 to your computer and use it in GitHub Desktop.
Save jnthn/11127634 to your computer and use it in GitHub Desktop.
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