AnyEvent::HTTPD(3pm)

πŸ“¦
version 0.93 Β· 2 versions
  • 0.93 Β· debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 0.93 Β· ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– AnyEvent::HTTPD πŸ’–

okay bestie, gather round, because we're talking about AnyEvent::HTTPD β€” that's the manual name, and this whole thing is a 3pm page from the User Contributed Perl Documentation (iykyk, that's the CPAN man section). No cap, this is a good one.


✨ NAME ✨

AnyEvent::HTTPD β€” a simple lightweight event based web (application) server. it's giving "tiny server, big dreams" πŸ¦‹


🌸 VERSION 🌸

Version 0.93


πŸŽ€ SYNOPSIS πŸŽ€

like, here's the whole vibe in code form:

use AnyEvent::HTTPD;

my $httpd = AnyEvent::HTTPD->new (port => 9090);

$httpd->reg_cb (
   '/' => sub {
      my ($httpd, $req) = @_;

      $req->respond ({ content => ['text/html',
         "<html><body><h1>Hello World!</h1>"
         . "<a href=\"/test\">another test page</a>"
         . "</body></html>"
      ]});
   },
   '/test' => sub {
      my ($httpd, $req) = @_;

      $req->respond ({ content => ['text/html',
         "<html><body><h1>Test page</h1>"
         . "<a href=\"/\">Back to the main page</a>"
         . "</body></html>"
      ]});
   },
);

$httpd->run; # making a AnyEvent condition variable would also work
periodt. that last comment is literally in the source, and yes, making an AnyEvent condition variable instead would also work. πŸ’…

πŸ’œ DESCRIPTION πŸ’œ

so this module gives you a simple HTTPD for serving simple web application interfaces. it's completely event based and independent from any event loop β€” how? because it uses AnyEvent, obviously. main character energy. πŸ‘‘

ngl, its HTTP implementation is a bit hacky, so before you use this module, please make sure it actually works for you and for the deployment you're planning. and if you feel like it β€” feel free to improve the HTTP support and send in patches! we love a contributor moment. 🫢

also, the documentation is currently only the source code, but next versions of this module will hopefully be better documented. in the meantime, go look at the "samples/" directory in the AnyEvent::HTTPD distribution for basic starting points. πŸ’–


🌈 FEATURES 🌈

  • support for GET and POST requests.
  • support for HTTP 1.0 keep-alive.
  • processing of "x-www-form-urlencoded" and "multipart/form-data" ("multipart/mixed") encoded form parameters.
  • support for streaming responses.
  • with version 0.8 no more dependent on LWP for HTTP::Date.
  • (limited) support for SSL.

🧚 METHODS 🧚

the AnyEvent::HTTPD class inherits directly from AnyEvent::HTTPD::HTTPServer, which inherits the event callback interface from Object::Event.

event callbacks can be registered via the Object::Event API (go read the Object::Event docs for the deets, bestie).

for a list of available events, scroll down to the EVENTS section. πŸ‘‡

🌟 new (%args)

this is the constructor for an AnyEvent::HTTPD object. the %args hash may contain one of these key/value pairs:

  • host => $host β€” the TCP address the HTTP server will listen on. usually 0.0.0.0 (which is the default), for a public server, or 127.0.0.1 for a local server.
  • port => $port β€” the TCP port the HTTP server will listen on. if it's undefined, some free port will be used, and you can get it via the "port" method.
  • ssl => $tls_ctx β€” if this option is given, the server will listen for a SSL/TLS connection on the configured port. as $tls_ctx you can pass anything you can pass as "tls_ctx" to an AnyEvent::Handle object.

Example:

my $httpd =
   AnyEvent::HTTPD->new (
      port => 443,
      ssl  => { cert_file => "/path/to/my/server_cert_and_key.pem" }
   );

Or:

my $httpd =
   AnyEvent::HTTPD->new (
      port => 443,
      ssl  => AnyEvent::TLS->new (...),
   );
  • request_timeout => $seconds β€” sets the request timeout for connections. the default value is 60 seconds. ⏰
  • backlog => $int β€” the backlog argument defines the maximum length the queue of pending connections may grow to. the real maximum queue length will be 1.5 times more than the value you specify in the backlog argument. see also "man 2 listen". by default it will be set by AnyEvent::Socket"::tcp_server to 128.
  • connection_class => $class β€” a special parameter you can use to pass your own connection class to AnyEvent::HTTPD::HTTPServer. this is only of interest to you if you plan to subclass AnyEvent::HTTPD::HTTPConnection. πŸ‘€
  • request_class => $class β€” a special parameter you can use to pass your own request class to AnyEvent::HTTPD. this is only of interest to you if you plan to subclass AnyEvent::HTTPD::Request.
  • allowed_methods => $arrayref β€” this sets the allowed HTTP methods for requests, defaulting to GET, HEAD and POST. each request received is matched against this list, and a '501 not implemented' is returned if no match is found. requests using disallowed handlers will never trigger callbacks. 🚫

🌟 port

returns the port number this server is bound to.

🌟 host

returns the host/ip this server is bound to.

🌟 allowed_methods

returns an arrayref of allowed HTTP methods, possibly as set by the allowed_methods argument to the constructor.

🌟 stop_request

when the server walks the request URI path upwards, you can stop the walk by calling this method. you can even stop further handling after the "request" event.

Example:

$httpd->reg_cb (
   '/test' => sub {
      my ($httpd, $req) = @_;

      # ...

      $httpd->stop_request; # will prevent that the callback below is called
   },
   '' => sub { # this one wont be called by a request to '/test'
      my ($httpd, $req) = @_;

      # ...
   }
);

🌟 run

this method is a simplification of the "AnyEvent" condition variable idiom. you can use it instead of writing:

my $cvar = AnyEvent->condvar;
$cvar->wait;

🌟 stop

this will stop the HTTP server and return from the "run" method β€” if you started the server via that method! βœ‹


πŸ’… EVENTS πŸ’…

every request goes to a specific URL. after a (GET or POST) request is received, the URL's path segments are walked down, and for each segment an event is generated. an example:

if the URL /test/bla.jpg is requested, the following events will be generated:

'/test/bla.jpg' - the event for the last segment
'/test'         - the event for the 'test' segment
''              - the root event of each request

to actually handle any request you just have to register a callback for the event name with the empty string. to handle all requests in the /test directory you have to register a callback for the event with the name /test. here's an example of how to register an event for the example URL above:

$httpd->reg_cb (
   '/test/bla.jpg' => sub {
      my ($httpd, $req) = @_;

      $req->respond ([200, 'ok', { 'Content-Type' => 'text/html' }, '<h1>Test</h1>' }]);
   }
);

see also "stop_request" about stopping the walk of the path segments. πŸ›‘

the first argument to such a callback is always the AnyEvent::HTTPD object itself. the second argument ($req) is the AnyEvent::HTTPD::Request object for this request. it can be used to get the (possible) form parameters for this request or the transmitted content, and to respond to the request. 🎁

along with the above mentioned events, these events are also provided:

  • request => $req β€” every request also emits the "request" event, with the same arguments and semantics as the above mentioned path request events. you can use this to implement your own request multiplexing. you can use "stop_request" to stop any further processing of the request, as the "request" event is the first thing that is executed for an incoming request.

an example of one of many possible uses:

$httpd->reg_cb (
   request => sub {
      my ($httpd, $req) = @_;

      my $url = $req->url;

      if ($url->path =~ /\/images\/img_(\d+).jpg$/) {
         handle_image_request ($req, $1); # your task :)

         # stop the request from emitting further events
         # so that the '/images/img_001.jpg' and the
         # '/images' and '' events are NOT emitted:
         $httpd->stop_request;
      }
   }
);
  • client_connected => $host, $port
  • client_disconnected => $host, $port

these events are emitted whenever a client coming from "$host:$port" connects to your server or is disconnected from it. πŸ«‚


πŸ“ CACHING πŸ“

any response from the HTTP server will have "Cache-Control" set to "max-age=0" and also the "Expires" header set to the "Date" header. meaning: caching is disabled. πŸ’€

you can of course set those headers yourself in the response, or remove them by setting them to undef, but keep in mind that the default for those headers is like mentioned above.

if you need more support here you can send me a mail β€” or even better: a patch :) 🌸


πŸ’– AUTHOR πŸ’–

Robin Redeker, "<elmex at ta-sa.org>"


πŸ› BUGS πŸ›

please report any bugs or feature requests to "bug-bs-httpd at rt.cpan.org", or through the web interface at <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=AnyEvent-HTTPD>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. fr fr, that's the deal. 🀝


🌟 SUPPORT 🌟

you can find documentation for this module with the perldoc command.

perldoc AnyEvent::HTTPD

you can also look for information at:


🫢 ACKNOWLEDGEMENTS 🫢

  • Andrey Smirnov β€” for keep-alive patches.
  • Pedro Melo β€” for valuable input in general and patches.
  • Nicholas Harteau β€” patch for ';' pair separator support, patch for allowed_methods support.
  • Chris Kastorff β€” patch for making default headers removable and more fault tolerant w.r.t. case.
  • Mons Anderson β€” Optimizing the regexes in AnyEvent::HTTPD::HTTPConnection and adding the backlog option to AnyEvent::HTTPD.

these people ate and left no crumbs, we love them for it. πŸ‘‘βœ¨


Copyright 2008-2011 Robin Redeker, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


and that's the whole page, bestie!! πŸ’–βœ¨πŸŽ€πŸ¦‹πŸŒΈπŸ’…

this little masterpiece is from perl v5.34.0, dated 2022-06-05, and it's the AnyEvent::HTTPD(3pm) page β€” so yeah, go build something cute with it. mwah. πŸ˜˜πŸ’œ

πŸ“¦ where this page comes from