NAME
POE::Component::Server::SimpleHTTP - Perl extension to serve HTTP requests in POE.
SYNOPSIS
use POE;
use POE::Component::Server::SimpleHTTP;
# Start the server!
POE::Component::Server::SimpleHTTP->new(
'ALIAS' => 'HTTPD',
'ADDRESS' => '192.168.1.1',
'PORT' => 11111,
'HOSTNAME' => 'MySite.com',
'HANDLERS' => [
{
'DIR' => '^/bar/.*',
'SESSION' => 'HTTP_GET',
'EVENT' => 'GOT_BAR',
},
{
'DIR' => '^/$',
'SESSION' => 'HTTP_GET',
'EVENT' => 'GOT_MAIN',
},
{
'DIR' => '^/foo/.*',
'SESSION' => 'HTTP_GET',
'EVENT' => 'GOT_NULL',
},
{
'DIR' => '.*',
'SESSION' => 'HTTP_GET',
'EVENT' => 'GOT_ERROR',
},
],
# In the testing phase...
'SSLKEYCERT' => [ 'public-key.pem', 'public-cert.pem' ],
) or die 'Unable to create the HTTP Server';
# Create our own session to receive events from SimpleHTTP
POE::Session->create(
inline_states => {
'_start' => sub { $_[KERNEL]->alias_set( 'HTTP_GET' );
$_[KERNEL]->post( 'HTTPD', 'GETHANDLERS', $_[SESSION], 'GOT_HANDLERS' );
},
'GOT_BAR' => \&GOT_REQ,
'GOT_MAIN' => \&GOT_REQ,
'GOT_ERROR' => \&GOT_ERR,
'GOT_NULL' => \&GOT_NULL,
'GOT_HANDLERS' => \&GOT_HANDLERS,
},
);
# Start POE!
POE::Kernel->run();
sub GOT_HANDLERS {
# ARG0 = HANDLERS array
my $handlers = $_[ ARG0 ];
# Move the first handler to the last one
push( @$handlers, shift( @$handlers ) );
# Send it off!
$_[KERNEL]->post( 'HTTPD', 'SETHANDLERS', $handlers );
}
sub GOT_NULL {
# ARG0 = HTTP::Request object, ARG1 = HTTP::Response object, ARG2 = the DIR that matched
my( $request, $response, $dirmatch ) = @_[ ARG0 .. ARG2 ];
# Kill this!
$_[KERNEL]->post( 'HTTPD', 'CLOSE', $response );
}
sub GOT_REQ {
# ARG0 = HTTP::Request object, ARG1 = HTTP::Response object, ARG2 = the DIR that matched
my( $request, $response, $dirmatch ) = @_[ ARG0 .. ARG2 ];
# Do our stuff to HTTP::Response
$response->code( 200 );
$response->content( 'Some funky HTML here' );
# We are done!
# For speed, you could use $_[KERNEL]->call( ... )
$_[KERNEL]->post( 'HTTPD', 'DONE', $response );
}
sub GOT_ERR {
# ARG0 = HTTP::Request object, ARG1 = HTTP::Response object, ARG2 = the DIR that matched
my( $request, $response, $dirmatch ) = @_[ ARG0 .. ARG2 ];
# Check for errors
if ( ! defined $request ) {
$_[KERNEL]->post( 'HTTPD', 'DONE', $response );
return;
}
# Do our stuff to HTTP::Response
$response->code( 404 );
$response->content( "Hi visitor from " . $response->connection->remote_ip . ", Page not found -> '" . $request->uri->path . "'" );
# We are done!
# For speed, you could use $_[KERNEL]->call( ... )
$_[KERNEL]->post( 'HTTPD', 'DONE', $response );
}
ABSTRACT
An easy to use HTTP daemon for POE-enabled programs
CHANGES
1.11
Fixed the bug where no HEADERS resulted in a explosion, thanks BinGOs!
PreForking added, look at SimpleHTTP::PreFork, thanks Stephen!
1.10
Rearranged some DEBUG printouts
Added some more 'return 1;' for POEization
Fixed STOPLISTEN/STARTLISTEN error
Added experimental SSL support via PoCo::SSLify
1.09
Fixed a small bug regarding the timing of SHUTDOWN GRACEFUL
I always forget to supply the session parameter to $kernel->call() :X
1.08
Made the SHUTDOWN event more smarter with the 'GRACEFUL' argument
Added the STARTLISTEN event to complement the STOPLISTEN event
Caught a minor bug -> If the client closed the socket and SimpleHTTP got an socket error, it will delete the wheel, resulting in confusion when we get the DONE/CLOSE event
Added $response->connection->dead boolean argument to check for the presence of a dead client
Re-jigging of internals ;)
Documented the only way to leak memory in SimpleHTTP ( hopefully heh )
Added the end-run leak checking to bite programmers that discard SimpleHTTP::Response objects :-)
I am considering putting SimpleHTTP::Response, HTTP::Request, SimpleHTTP::Connection into one super-object, called SimpleHTTP::Request
This object will have the HTTP::Request, HTTP::Response, SimpleHTTP::Connection objects hanging off it:
$client->request() # HTTP::Request
$client->response() # HTTP::Response
$client->connection() # SimpleHTTP::Connection
If I get enough ayes from people, I will go ahead and implement this change for a cleaner design.
E-MAIL me your opinion or it will be ignored :)
1.07
Added the STOPLISTEN event, to make it shutdown the listening socket to help larger programs shutdown cleanly
Removed the CHANGES file, as it is redundant :)
Added "return 1;" everywhere I could to avoid the nasty copy-on-exit POE bug squashed in 1.05
1.06
Fixed SHUTDOWN to cleanly kill sockets, checking for definedness first
Fixed new() to remove options that exist, but is undef -> results in croaking when DEBUG is on
Added the CLOSE event to kill sockets without sending any output
1.05
Got rid of POE::Component::Server::TCP and replaced it with POE::Wheel::SocketFactory for speed/efficiency
As the documentation for POE::Filter::HTTPD says, updated POD to reflect the HTTP::Request/Response issue
Got rid of SimpleHTTP::Request, due to moving of the Connection object to Response
-> Found a circular leak by having SimpleHTTP::Connection in SimpleHTTP::Request, to get rid of it, moved it to Response
-> Realized that sometimes HTTP::Request will be undef, so how would you get the Connection object?
Internal tweaking to save some memory
Added the MAX_RETRIES subroutine
More extensive DEBUG statements
POD updates
Paul Visscher tracked down the HTTP::Request object leak, thanks!
Cleaned up the Makefile.PL
Benchmarked and found a significant speed difference between post()ing and call()ing the DONE event
-> The call() method is ~8% faster
-> However, the chance of connecting sockets timing out is greater...
1.04
Fixed a bug reported by Tim Wood about socket disappearing
Fixed *another* bug in the Connection object, pesky CaPs! ( Again, reported by Tim Wood )
1.03
Added the GETHANDLERS/SETHANDLERS event
POD updates
Fixed SimpleHTTP::Connection to get rid of the funky CaPs
1.02
Small fix regarding the Got_Error routine for Wheel::ReadWrite
1.01
Initial Revision
DESCRIPTION
This module makes serving up HTTP requests a breeze in POE.
The hardest thing to understand in this module is the HANDLERS. That's it!
The standard way to use this module is to do this:
use POE;
use POE::Component::Server::SimpleHTTP;
POE::Component::Server::SimpleHTTP->new( ... );
POE::Session->create( ... );
POE::Kernel->run();
Starting SimpleHTTP
To start SimpleHTTP, just call it's new method:
POE::Component::Server::SimpleHTTP->new(
'ALIAS' => 'HTTPD',
'ADDRESS' => '192.168.1.1',
'PORT' => 11111,
'HOSTNAME' => 'MySite.com',
'HEADERS' => {},
'HANDLERS' => [ ],
);
This method will die on error or return success.
This constructor accepts only 7 options.
ALIAS
-
This will set the alias SimpleHTTP uses in the POE Kernel. This will default to "SimpleHTTP"
ADDRESS
-
This value will be passed to POE::Component::Server::TCP to bind to.
PORT
-
This value will be passed to POE::Component::Server::TCP to bind to.
HOSTNAME
-
This value is for the HTTP::Request's URI to point to. If this is not supplied, SimpleHTTP will use Sys::Hostname to find it.
HEADERS
-
This should be a hashref, that will become the default headers on all HTTP::Response objects. You can override this in individual requests by setting it via $request->header( ... )
For more information, consult the HTTP::Headers module.
HANDLERS
-
This is the hardest part of SimpleHTTP :)
You supply an array, with each element being a hash. All the hashes should contain those 3 keys:
DIR -> The regexp that will be used, more later.
SESSION -> The session to send the input
EVENT -> The event to trigger
The DIR key should be a valid regexp. This will be matched against the current request path. Pseudocode is: if ( $path =~ /$DIR/ )
NOTE: The path is UNIX style, not MSWIN style ( /blah/foo not \blah\foo )
Now, if you supply 100 handlers, how will SimpleHTTP know what to do? Simple! By passing in an array in the first place, you have already told SimpleHTTP the order of your handlers. They will be tried in order, and if a match is not found, SimpleHTTP will DIE!
This allows some cool things like specifying 3 handlers with DIR of: '^/foo/.*', '^/$', '.*'
Now, if the request is not in /foo or not root, your 3rd handler will catch it, becoming the "404 not found" handler!
NOTE: You might get weird Session/Events, make sure your handlers are in order, for example: '^/', '^/foo/.*' The 2nd handler will NEVER get any requests, as the first one will match ( no $ in the regex )
Now, here's what a handler receives:
ARG0 -> HTTP::Request object
ARG1 -> POE::Component::Server::SimpleHTTP::Response object
ARG2 -> The exact DIR that matched, so you can see what triggered what
NOTE: If ARG0 is undef, that means POE::Filter::HTTPD encountered an error parsing the client request, simply modify the HTTP::Response object and send some sort of generic error. SimpleHTTP will set the path used in matching the DIR regexes to an empty string, so if there is a "catch-all" DIR regex like '.*', it will catch the errors, and only that one.
NOTE: The only way SimpleHTTP will leak memory ( hopefully heh ) is if you discard the SimpleHTTP::Response object without sending it back to SimpleHTTP via the DONE/CLOSE events, so never do that!
SSLKEYCERT
-
This should be an arrayref of only 2 elements - the public key and certificate location. Now, this is still in the experimental stage, and testing is greatly welcome!
Again, this will automatically turn every incoming connection into a SSL socket. Once enough testing has been done, this option will be augmented with more SSL stuff!
Events
SimpleHTTP is so simple, there are only 7 events available.
DONE
-
This event accepts only one argument: the HTTP::Response object we sent to the handler. Calling this event implies that this particular request is done, and will proceed to close the socket. NOTE: This method automatically sets those 3 headers if they are not already set: Date -> Current date stringified via HTTP::Date->time2str Content-Type -> text/html Content-Length -> length( $response->content ) To get greater throughput and response time, do not post() to the DONE event, call() it! However, this will force your program to block while servicing web requests...
CLOSE
-
This event accepts only one argument: the HTTP::Response object we sent to the handler. Calling this event will close the socket, not sending any output
GETHANDLERS
-
This event accepts 2 arguments: The session + event to send the response to This event will send back the current HANDLERS array ( deep-cloned via Storable::dclone ) The resulting array can be played around to your tastes, then once you are done...
SETHANDLERS
-
This event accepts only one argument: pointer to HANDLERS array BEWARE: if there is an error in the HANDLERS, SimpleHTTP will die!
STARTLISTEN
-
Starts the listening socket, if it was shut down
STOPLISTEN
-
Simply a wrapper for SHUTDOWN GRACEFUL, but will not shutdown SimpleHTTP if there is no more requests
SHUTDOWN
-
Without arguments, SimpleHTTP does this: Close the listening socket Kills all pending requests by closing their sockets Removes it's alias With an argument of 'GRACEFUL', SimpleHTTP does this: Close the listening socket Waits for all pending requests to come in via DONE/CLOSE, then removes it's alias
SimpleHTTP Notes
This module is very picky about capitalization!
All of the options are uppercase, to avoid confusion.
You can enable debugging mode by doing this:
sub POE::Component::Server::SimpleHTTP::DEBUG () { 1 }
use POE::Component::Server::SimpleHTTP;
Also, this module will try to keep the Listening socket alive. if it dies, it will open it again for a max of 5 retries.
You can override this behavior by doing this:
sub POE::Component::Server::SimpleHTTP::MAX_RETRIES () { 10 }
use POE::Component::Server::SimpleHTTP;
For those who are pondering about basic-authentication, here's a tiny snippet to put in the Event handler
# Contributed by Rocco Caputo
sub Got_Request {
# ARG0 = HTTP::Request, ARG1 = HTTP::Response
my( $request, $response ) = @_[ ARG0, ARG1 ];
# Get the login
my ( $login, $password ) = $request->authorization_basic();
# Decide what to do
if ( ! defined $login or ! defined $password ) {
# Set the authorization
$response->header( 'WWW-Authenticate' => 'Basic realm="MyRealm"' );
$response->code( 401 );
$response->content( 'FORBIDDEN.' );
# Send it off!
$_[KERNEL]->post( 'SimpleHTTP', 'DONE', $response );
} else {
# Authenticate the user and move on
}
}
EXPORT
Nothing.
SEE ALSO
L<POE>
L<POE::Filter::HTTPD>
L<HTTP::Request>
L<HTTP::Response>
L<POE::Component::Server::SimpleHTTP::Connection>
L<POE::Component::Server::SimpleHTTP::Response>
L<POE::Component::Server::SimpleHTTP::PreFork>
L<POE::Component::SSLify>
AUTHOR
Apocalypse <apocal@cpan.org>
COPYRIGHT AND LICENSE
Copyright 2005 by Apocalypse
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.