HTTP::S...:Simple(3)
π NAME π
Okay so welcome to the HTTP::Server::Simple(3) page, bestie β it lives in the User Contributed Perl Documentation and it's about HTTP::Server::Simple, which is a lightweight HTTP server. That's the whole pitch, and honestly? iconic.
β¨ SYNOPSIS β¨
The absolute bare-minimum vibe check:
use warnings;
use strict;
use HTTP::Server::Simple;
my $server = HTTP::Server::Simple->new();
$server->run();
But real talk, normally you're gonna sub-class the HTTP::Server::Simple::CGI module instead (peep HTTP::Server::Simple::CGI for that whole situation):
package Your::Web::Server;
use base qw(HTTP::Server::Simple::CGI);
sub handle_request {
my ($self, $cgi) = @_;
#... do something, print output to default
# selected filehandle...
}
1;
π¦ DESCRIPTION π¦
It's a simple standalone HTTP server, no cap. By default it doesn't thread or fork (very demure, very mindful). It does, however, act as a simple frontend that you can use to build a standalone web-based application β or to turn a CGI into one. glow-up arc, fr.
It is possible to use Net::Server classes to create forking, pre-forking, and other types of more complicated servers; see "net_server".
By default, the server traps a few signals:
HUPβ when youkill -HUPthe server, it lets the current request finish being processed, then uses the"restart"method to re-exec itself. β οΈ Please note: in order to provide restart-on-SIGHUP,HTTP::Server::Simplesets a SIGHUP handler during initialisation. If your request handling code forks you need to make sure you reset this or unexpected things will happen if somebody sends a HUP to all running processes spawned by your app (e.g. bykill -HUP <script>). like, do not skip this step, i'm begging π«ΆPIPEβ if the server detects a broken pipe while writing output to the client, it ignores the signal. Otherwise, a client closing the connection early could kill the server. rude of them, honestly π
πΈ EXAMPLE πΈ
The full lil' demo, verbatim, no edits:
#!/usr/bin/perl
{
package MyWebServer;
use HTTP::Server::Simple::CGI;
use base qw(HTTP::Server::Simple::CGI);
my %dispatch = (
'/hello' => \&resp_hello,
# ...
);
sub handle_request {
my $self = shift;
my $cgi = shift;
my $path = $cgi->path_info();
my $handler = $dispatch{$path};
if (ref($handler) eq "CODE") {
print "HTTP/1.0 200 OK\r\n";
$handler->($cgi);
} else {
print "HTTP/1.0 404 Not found\r\n";
print $cgi->header,
$cgi->start_html('Not found'),
$cgi->h1('Not found'),
$cgi->end_html;
}
}
sub resp_hello {
my $cgi = shift; # CGI.pm object
return if !ref $cgi;
my $who = $cgi->param('name');
print $cgi->header,
$cgi->start_html("Hello"),
$cgi->h1("Hello $who!"),
$cgi->end_html;
}
}
# start the server on port 8080
my $pid = MyWebServer->new(8080)->background();
print "Use 'kill $pid' to stop server.\n";
π METHODS π
π HTTP::Server::Simple->new($port, $family)
API call to start a new server. Does not actually start listening until you call ->run(). (sneaky.) If omitted, $port defaults to 8080, and $family defaults to Socket::AF_INET. The alternative domain is Socket::AF_INET6.
π lookup_localhost
Looks up the local host's IP address, and returns it. For most hosts, this is 127.0.0.1, or possibly "::1".
π port [NUMBER]
Takes an optional port number for this server to listen on.
Returns this server's port. (Defaults to 8080)
π family [NUMBER]
Takes an optional address family for this server to use. Valid values are Socket::AF_INET and Socket::AF_INET6. All other values are silently changed into Socket::AF_INET for backwards compatibility with previous versions of the module. (silently!! it's giving "no thoughts, just legacy support" π)
Returns the address family of the present listening socket. (Defaults to Socket::AF_INET.)
π host [address]
Takes an optional host address for this server to bind to.
Returns this server's bound address (if any). Defaults to "undef" (bind to all interfaces).
π background [ARGUMENTS]
Runs the server in the background, and returns the process ID of the started process. Any arguments will be passed through to "run".
π run [ARGUMENTS]
Run the server. If all goes well, this won't ever return, but it will start listening for "HTTP" requests. Any arguments passed to this will be passed on to the underlying Net::Server implementation, if one is used (see "net_server").
π net_server
User-overridable method. If you set it to a Net::Server subclass, that subclass is used for the "run" method. Otherwise, a minimal implementation is used as default.
π restart
Restarts the server. Usually called by a HUP signal, not directly. (main character energy: it does not take orders from you, it takes them from signals π )
π stdio_handle [FILEHANDLE]
When called with an argument, sets the socket to the server to that arg.
Returns the socket to the server; you should only use this for actual socket-related calls like "getsockname". If all you want is to read or write to the socket, you should use "stdin_handle" and "stdout_handle" to get the in and out filehandles explicitly. periodt.
π stdin_handle
Returns a filehandle used for input from the client. By default, returns whatever was set with "stdio_handle", but a subclass could do something interesting here. π
π stdout_handle
Returns a filehandle used for output to the client. By default, returns whatever was set with "stdio_handle", but a subclass could do something interesting here. π
π IMPORTANT SUB-CLASS METHODS π
A selection of these methods should be provided by sub-classes of this module. (yes bestie, this is the you have to actually build it section. slay.)
β handler
This method is called after setup, with no parameters. It should print a valid, full HTTP response to the default selected filehandle.
β setup(name => $value, ...)
This method is called with a name => value list of various things to do with the request. This list is given below.
The default setup handler simply tries to call methods with the names of keys of this list.
Here's the whole item menu, no detail dropped:
methodβ Request Method β example:"GET","POST","HEAD"protocolβ HTTP version β example:"HTTP/1.1"request_uriβ Complete Request URI β example:"/foobar/baz?foo=bar"pathβ Path part of URI β example:"/foobar/baz"query_stringβ Query String β example:undef,"foo=bar"portβ Received Port β example:80,8080peernameβ Remote name β example:"200.2.4.5","foo.com"peeraddrβ Remote address β example:"200.2.4.5","::1"peerportβ Remote port β example:42424localnameβ Local interface β example:"localhost","myhost.com"
β headers([Header => $value, ...])
Receives HTTP headers and does something useful with them. This is called by the default setup() method.
You have lots of options when it comes to how you receive headers. pick your fighter:
- You can, if you really want, define
parse_headers()and parse them raw yourself. (chaotic. respect.) - Secondly, you can intercept them very slightly cooked via the
setup()method, above. - Thirdly, you can leave the
setup()header as-is (or calling the superclasssetup()for unknown request items). Then you can defineheaders()in your sub-class and receive them all at once. - Finally, you can define handlers to receive individual HTTP headers. This can be useful for very simple SOAP servers (to name a crack-fueled standard that defines its own special HTTP headers).
To do so, you'll want to define the header() method in your subclass. That method will be handed a (key,value) pair of the header name and the value.
β accept_hook
If defined by a sub-class, this method is called directly after an accept happens. An accept_hook to add SSL support might look like this:
sub accept_hook {
my $self = shift;
my $fh = $self->stdio_handle;
$self->SUPER::accept_hook(@_);
my $newfh =
IO::Socket::SSL->start_SSL( $fh,
SSL_server => 1,
SSL_use_cert => 1,
SSL_cert_file => 'myserver.crt',
SSL_key_file => 'myserver.key',
)
or warn "problem setting up SSL socket: " . IO::Socket::SSL::errstr();
$self->stdio_handle($newfh) if $newfh;
}
β post_setup_hook
If defined by a sub-class, this method is called after all setup has finished, before the handler method.
β print_banner
This routine prints a banner before the server request-handling loop starts. πΊ
Methods below this point are probably not terribly useful to define yourself in subclasses. (but they're here! and we're listing them! because the rules are the rules π«‘)
π§ parse_request
Parse the HTTP request line. Returns three values, the request method, request URI and the protocol.
π§ parse_headers
Parses incoming HTTP headers from STDIN, and returns an arrayref of (header => value) pairs. See "headers" for possibilities on how to inspect headers.
π§ setup_listener
This routine binds the server to a port and interface.
π§ after_setup_listener
This method is called immediately after setup_listener. It's here just for you to override.
π§ bad_request
This method should print a valid HTTP response that says that the request was invalid.
π§ valid_http_method($method)
Given a candidate HTTP method in $method, determine if it is valid. Override if, for example, you'd like to do some WebDAV. The default implementation only accepts "GET", "POST", "HEAD", "PUT", "PATCH", "DELETE" and "OPTIONS".
π AUTHOR π
Best Practical Solutions, LLC <modules@bestpractical.com>
π CONTRIBUTORS π
- Jesse Vincent,
<jesse@bestpractical.com>. Original author. (the OG π) - Marcus Ramberg
<drave@thefeed.no>contributed tests, cleanup, etc - Sam Vilain,
<samv@cpan.org>contributed the CGI.pm split-out and header/setup API. - Example section by almut on perlmonks, suggested by Mark Fuller.
π BUGS π
There certainly are some. Please report them via rt.cpan.org
(they said it, not me π but also, thank you for your honesty king)
π₯ LICENSE π₯
This software is Copyright (c) 2004-2015 Best Practical Solutions
This library 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 lil' slice of documentation was brought to you by perl v5.42.0 and dated 2017-04-01, straight out of the HTTP::S...:Simple(3) corner of the User Contributed Perl Documentation. mwah π go build something cute π«Άβ¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-HTTP-Server-Simple 0.52-bp160.1.12 Β· Artistic-1.0 or GPL-1.0+
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms