Created
October 15, 2017 19:05
-
-
Save gfldex/044cdfa4e6bdf680c9a22e39e7b95e23 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
use v6.c; | |
# use v6.d.PREVIEW; | |
my sub term:<now>() { DateTime.now.Instant but role :: { method Str { self.DateTime.hh-mm-ss } } }; | |
constant HTTP-HEADER = "HTTP/1.1 200 OK", "Content-Type: text/plain; charset=UTF-8", "Content-Encoding: UTF-8", ""; | |
constant term:<HTTP-HEADER-404> = "HTTP/1.1 404 Not Found", "Content-Type: text/plain; charset=UTF-8", "Content-Encoding: UTF-8", ""; | |
my &BOLD = $*OUT.t ?? sub (*@s) { "\e[1m{@s.join('')}\e[0m" } !! sub (|c) { c }; | |
react { | |
whenever IO::Socket::Async.listen('0.0.0.0', 8080) -> $conn { | |
note „{now} incomming connection from {$conn.peer-host}:{$conn.peer-port}“; | |
my @msg = HTTP-HEADER; | |
whenever $conn.Supply.lines { | |
# we only really care about the first line in a http header. | |
if /^GET <ws> (<[\w„/“]>+) [„HTTP“ \d „/“ \d]? / { | |
note „{now} GET $0“; | |
given $0.Str { | |
when „/status“ { | |
@msg.push: „running since {BEGIN now} UTC“; | |
} | |
when „/“ { | |
@msg[1] = ‚Content-Type: application/xhtml+xml; charset=UTF-8‘; | |
@msg.push: ‚html/index.xhtml‘.IO.slurp; | |
} | |
when „/exit“ { | |
done; | |
} | |
default { | |
@msg = HTTP-HEADER-404; | |
@msg.push: „Resource {.Str} not found.“; | |
} | |
} | |
} | |
# `lines` returns the empty string on a double newline, as we get at the end of a http header. | |
if /^$/ { | |
for @msg { | |
once note .Str; | |
$conn.print(.Str ~ "\n"); | |
} | |
$conn.close; | |
} | |
} | |
CLOSE { | |
note „{now} connection closed“; | |
} | |
CATCH { default { warn BOLD .^name, ': ', .Str; warn BOLD „handled in $?LINE“; } } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment