This simple web server sends its own source back to the browser.

The first thing this program does is create a Server::HTTP component. That will listen for requests on Port 32080. Its ContentHandler maps requests under the root directory ("/") to web_handler(). This means web_handler() will be called to generate content for "/" requests.

In other words, requests http://localhost:32080/ will fetch the program itself.

Content handlers such as web_handler() receive two parameters. The first is an HTTP::Request object representing the user's request. The second parameter is an empty HTTP::Response object suitable for filling in with custom content.

See the documentation for [HTTP::Request] and [HTTP::Response] for more information.

In this program, web_handler() fills in its HTTP::Response object with the program's own source. It reads the source via the DATA filehandle, which Perl has opened in response to the __END__ marker below.

use warnings;
use strict;
use POE;
use POE::Component::Server::HTTP;
use HTTP::Status qw/RC_OK/;
  Port           => 32080,
  ContentHandler => {"/" => \&web_handler},
  Headers => {Server => 'POE Cookbook POE::Component::Server::HTTP Sample',},

sub web_handler {
  my ($request, $response) = @_;

  # Slurp in the program's source.
  seek(DATA, 0, 0);
  local $/;
  my $source = <DATA>;

  # Build the response.
  $response->push_header("Content-Type", "text/plain");
  $response->content("This program's source:\n\n$source");

  # Signal that the request was handled okay.
  return RC_OK;
Thanks to Arthur Bergman for writing this spiffy component.
<dngor> What's the term for a program that displays its own source?
<merlyn> quine
This program is not a quine, however, because it cheats by reading
its source from a file.