Skip to content
Browse files

Much nicer log messages, debugging, and more hooks.

  • Loading branch information...
1 parent 634d120 commit c727381984f672c25dc732173db7d72bd2c37973 @supernovus committed
Showing with 26 additions and 6 deletions.
  1. +2 −1 examples/test.p6
  2. +24 −5 lib/HTTP/Easy.pm6
View
3 examples/test.p6
@@ -8,6 +8,7 @@ my $app = sub (%env) {
return [ 200, [ 'Content-Type' => 'text/plain' ], [ "Hello World" ] ];
}
-my $server = HTTP::Easy::PSGI.new;
+## We are using :debug for more detailed output to STDERR.
+my $server = HTTP::Easy::PSGI.new(:debug);
$server.app($app);
$server.run;
View
29 lib/HTTP/Easy.pm6
@@ -6,19 +6,34 @@
class HTTP::Easy {
has Int $.port = 8080;
has Str $.host = 'localhost';
+ has Bool $.debug = False;
has $!listener = IO::Socket::INET.new(:localhost($.host), :localport($.port), :listen(1));
has $.connection is rw; ## To be populated by accept().
has %.env; ## The environment, generated by run().
has $.body is rw; ## Any request body, populated by run().
+ ## We're using DateTime.new(time) instead of DateTime.now()
+ ## Because the current DateTime messes up the user's local timezone
+ ## if they are in a negative offset, which totally screws up the reported
+ ## time, so we are forcing UTC instead.
+ sub message ($message) {
+ my $timestamp = DateTime.new(time).Str;
+ $*ERR.say: "$timestamp -- $message";
+ }
+
method run {
- $*ERR.say: "{time} Started HTTP server.";
+ message('Started HTTP server.');
self.pre-connection;
while $.connection = $!listener.accept {
self.on-connection;
+ if ($.debug) { message("Client connection opened."); }
my $received = $!connection.recv();
+ if ($.debug) { message("Got HTTP request:\n$received"); }
my @request = split("\x0D\x0A", $received);
my $request = shift @request;
+ if (! $.debug) { ## This is shown when not debugging.
+ message($request);
+ }
my ($method, $uri, $protocol) = $request.split(/\s/);
if (!$protocol) { $protocol = 'HTTP/1.1'; }
unless $method eq any(<GET POST HEAD PUT DELETE>) { die "unknown HTTP method"; }
@@ -54,13 +69,17 @@ class HTTP::Easy {
$!connection.send($res);
}
$!connection.close;
- }
+ self.closed-connection;
+ }
+ self.finish-connection;
}
## Stub methods. Replace with your own.
- method pre-connection {};
- method on-connection {};
- method handler {}; ## This MUST be implemented.
+ method pre-connection {}; ## Runs prior to waiting for connection.
+ method on-connection {}; ## Runs at the beginning of each connection.
+ method closed-connection {}; ## Runs after closing each connection.
+ method finished-connection {}; ## Runs when the wait loop is ended.
+ method handler {}; ## The HTTP request handler (MANDATORY).
}

0 comments on commit c727381

Please sign in to comment.
Something went wrong with that request. Please try again.