POE::Co...r::HTTP(3)

πŸ“¦
version 0.09 Β· 2 versions
, in fedora 43

πŸŽ€ NAME πŸŽ€

POE::Component::Server::HTTP β€” the foundation of a POE HTTP daemon, bestie πŸ’–


✨ SYNOPSIS ✨

okay so here's the vibe, copy-paste core:

use POE::Component::Server::HTTP;
use HTTP::Status;
my $aliases = POE::Component::Server::HTTP->new(
    Port => 8000,
    ContentHandler => {
          '/' => \&handler1,
          '/dir/' => sub { ... },
          '/file' => sub { ... }
    },
    Headers => { Server => 'My Server' },
 );

 sub handler {
     my ($request, $response) = @_;
     $response->code(RC_OK);
     $response->content("Hi, you fetched ". $request->uri);
     return RC_OK;
 }

 POE::Kernel->call($aliases->{httpd}, "shutdown");
 # next line isn't really needed
 POE::Kernel->call($aliases->{tcp}, "shutdown");

🌸 DESCRIPTION 🌸

POE::Component::Server::HTTP (aka PoCo::HTTPD, that's the nickname, iykyk) is a framework for building your own custom HTTP servers on top of POE. It's loosely modeled on the ideas of apache and the mod_perl/Apache module. Loosely. Like, spiritually. πŸ¦‹

It is built a lot on work done by Gisle Aas on the HTTP::* modules and the URI module, which are subclassed. Shoutout Gisle, icon behavior honestly. πŸ‘‘

PoCo::HTTPD lets you register different handlers, stacked by directory, that will be run during the course of the request. Stacked. By directory. Remember that. πŸ“š

πŸ’… Handlers πŸ’…

Handlers go on a stack in fifo order. The path /foo/bar/baz/honk.txt will first push the handlers of /, then of /foo/, then of /foo/bar/, then of /foo/bar/baz/, and lastly /foo/bar/baz/honk.txt. See the pattern? Slash by slash, baby. ✨

PAY ATTENTION TO DIRECTORIES! A request for /honk will not match /honk/ the way you're used to with apache. If you want /honk to act like a directory, you should have a handler for /honk which redirects to /honk/. Do not skip this, fr fr. 🚨

However β€” and this is the plot twist β€” there can be only one ContentHandler, and if any handler installs a ContentHandler, that will override the old ContentHandler. One. Singular. πŸ’€

If no handler installs a ContentHandler, it will find the closest one directory-wise and use it. Bless. 🫢

There's also a special StreamHandler, which is a coderef that gets invoked if you have turned on streaming by doing $response->streaming(1);

Handlers take the $request and $response objects as arguments. That's the whole deal. πŸ’–

Return codes, the moment you've been waiting for:

  • RC_OK β€” Everything is ok, please continue processing. The good ending. βœ…
  • RC_DENY β€” If it is a TransHandler, stop translation handling and carry on with a PreHandler; if it is a PostHandler, do nothing; else return denied to the client. (Yeah, it's conditional like that. Read it twice.) πŸ™ˆ
  • RC_WAIT β€” This is a special handler that suspends the execution of the handlers. They will be suspended until $response->continue() is called. This is useful if you want to do a long request and not blocck. (Yes, "blocck". We keep the typo, it's canon. 😭)

The following handlers are available. Here we go, the whole lineup: 🌈

TransHandler

TransHandlers are run before the URI has been resolved, giving them a chance to change the URI. Which means they can not be registred per directory. (Again: "registred". Canon. πŸ’…)

new(TransHandler => [ sub {return RC_OK} ]);

A TransHandler can stop the dispatching of TransHandlers and jump to the next handler type by specifing RC_DENY; ("specifing", also canon, we love consistency πŸŽ€)

PreHandler

PreHandlers are stacked by directory and run after TransHandler but before the ContentHandler. They can change ContentHandler (but beware, other PreHandlers might also change it πŸ‘€) and push on PostHandlers.

new(PreHandler => { '/' => [sub {}], '/foo/' => [\&foo]});

ContentHandler

The handler that is supposed to give the content. When this handler returns, it will send the response object to the client. It will automaticly add Content-Length and Date if these are not set. If the response is streaming, it will make sure the correct headers are set. It will also expand any cookies which have been pushed onto the response object. Cookies! πŸͺ

new(ContentHandler => { '/' => sub {}, '/foo/' => \&foo});

ErrorHandler

This handler is called when there is a read or write error on the socket. This is most likely caused by the remote side closing the connection. $resquest->is_error and $response->is_error will return true. (Yes, $resquest. Typo stays. That's the deal. 🫠)

Note: "PostHanlder" will still be called, but "TransHandler" and "PreHandler" won't be. (And yes, "PostHanlder". We're keeping that too. It's part of the family now. 😭)

It is a map to coderefs just like ContentHandler is.

PostHandler

These handlers are run after the socket has been flushed. 🚿

new(PostHandler => { '/' => [sub {}], '/foo/' => [\&foo]});

StreamHandler

If you turn on streaming in any other handler, the request is placed in streaming mode. This handler is called, with the usual parameters, when streaming mode is first entered, and subsequently when each block of data is flushed to the client.

Streaming mode is turned on via the $response object:

$response->streaming(1);

You deactivate streaming mode with the same object:

$response->close;

Content is also sent to the client via the $response object:

$response->send($somedata);

The output filter is set to POE::Filter::Stream, which passes the data through unchanged. If you are doing a multipart/mixed response, you will have to set up your own headers. Your headers, your problem, bestie. πŸ’…

Example:

sub new {
    .....
    POE::Component::Filter::HTTP->new(
             ContentHandler => { '/someurl' => sub { $self->someurl(@_) },
             StreamHandler  => sub { $self->stream(@_),
        );
}

sub someurl {
    my($self, $resquest, $response)=@_;
    $self->{todo} = [ .... ];
    $response->streaming(1);
    $response->code(RC_OK);         # you must set up your response header
    $response->content_type(...);

    return RC_OK;
}

sub stream {
    my($self, $resquest, $response)=@_;

    if( @{$self->{todo}} ) {
        $response->send(shift @{$self->{todo}});
    }
    else {
        $response->close;
    }
}

Another example can be found in t/30_stream.t. The parts dealing with multipart/mixed are well documented and at the end of the file. Go read it, it's giving study session. πŸ“–

NOTE: Changes in streaming mode are only verified when StreamHandler exits. So you must either turn streaming off in your StreamHandler, or make sure that the StreamHandler will be called again. This last is done by sending data to the client. If for some reason you have no data to send, you can get the same result with "continue". Remember that this will also cause the StreamHandler to be called one more time.
my $aliases=POE::Component::Filter::HTTP->new( ....);

# and then, when the end of the stream in met
$response->close;
$response->continue;
NOTE: even when the stream ends, the client connection will be held open if Keepalive is active. To force the connection closed, set the Connection header to close:
$resquest->header(Connection => 'close');

This might be a bug. Are there any cases where we'd want to keep the connection open after a stream? Genuine question, drop it in the group chat. πŸ€”


πŸ¦‹ Events πŸ¦‹

The "shutdown" event may be sent to the component, indicating that it should shut down. The event may be sent using the return value of the new() method (which is a session id) by either post()ing or call()ing.

I've experienced some problems with the session not receiving the event when it gets post()ed, so call() is advised. Not me warning you in advance 😭 β€” just use call().


🌈 See Also 🌈

Please also take a look at HTTP::Response, HTTP::Request, URI, POE and POE::Filter::HTTPD. Reading list, bestie. Obsessed. ✨


πŸ“ TODO πŸ“

  • Document Connection Response and Request objects.
  • Write more tests.
  • Add a PoCo::Server::HTTP::Session that matches a http session against poe session using cookies or other state system.
  • Add more options to streaming.
  • Figure out why post()ed "shutdown" events don't get received.
  • Probably lots of other API changes.

(Manifesting all of these. πŸ•―οΈ)


πŸ‘‘ AUTHOR πŸ‘‘

Arthur Bergman, arthur@contiller.se

Additional hacking by Philip Gwyn, poe-at-pied.nu

Released under the same terms as POE.


perl v5.42.0 Β· 2025-07-25 β€” and that's the whole page, bestie. Go build something iconic with it. slay, periodt πŸ’…βœ¨πŸ¦‹

πŸ“¦ where this page comes from