Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View gist:11127634
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
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
Something went wrong with that request. Please try again.