1HTTP::Server::Simple(3)User Contributed Perl DocumentatioHnTTP::Server::Simple(3)
2
3
4

NAME

6       HTTP::Server::Simple - Lightweight HTTP server
7

SYNOPSIS

9        use warnings;
10        use strict;
11
12        use HTTP::Server::Simple;
13
14        my $server = HTTP::Server::Simple->new();
15        $server->run();
16
17       However, normally you will sub-class the HTTP::Server::Simple::CGI
18       module (see HTTP::Server::Simple::CGI);
19
20        package Your::Web::Server;
21        use base qw(HTTP::Server::Simple::CGI);
22
23        sub handle_request {
24            my ($self, $cgi) = @_;
25
26            #... do something, print output to default
27            # selected filehandle...
28
29        }
30
31        1;
32

DESCRIPTION

34       This is a simple standalone HTTP server. By default, it doesn't thread
35       or fork. It does, however, act as a simple frontend which can be used
36       to build a standalone web-based application or turn a CGI into one.
37
38       It is possible to use Net::Server classes to create forking, pre-
39       forking, and other types of more complicated servers; see "net_server".
40
41       By default, the server traps a few signals:
42
43       HUP When you "kill -HUP" the server, it lets the current request finish
44           being processed, then uses the "restart" method to re-exec itself.
45           Please note that in order to provide restart-on-SIGHUP,
46           HTTP::Server::Simple sets a SIGHUP handler during initialisation.
47           If your request handling code forks you need to make sure you reset
48           this or unexpected things will happen if somebody sends a HUP to
49           all running processes spawned by your app (e.g. by "kill -HUP
50           <script>")
51
52       PIPE
53           If the server detects a broken pipe while writing output to the
54           client, it ignores the signal. Otherwise, a client closing the
55           connection early could kill the server.
56

EXAMPLE

58        #!/usr/bin/perl
59        {
60        package MyWebServer;
61
62        use HTTP::Server::Simple::CGI;
63        use base qw(HTTP::Server::Simple::CGI);
64
65        my %dispatch = (
66            '/hello' => \&resp_hello,
67            # ...
68        );
69
70        sub handle_request {
71            my $self = shift;
72            my $cgi  = shift;
73
74            my $path = $cgi->path_info();
75            my $handler = $dispatch{$path};
76
77            if (ref($handler) eq "CODE") {
78                print "HTTP/1.0 200 OK\r\n";
79                $handler->($cgi);
80
81            } else {
82                print "HTTP/1.0 404 Not found\r\n";
83                print $cgi->header,
84                      $cgi->start_html('Not found'),
85                      $cgi->h1('Not found'),
86                      $cgi->end_html;
87            }
88        }
89
90        sub resp_hello {
91            my $cgi  = shift;   # CGI.pm object
92            return if !ref $cgi;
93
94            my $who = $cgi->param('name');
95
96            print $cgi->header,
97                  $cgi->start_html("Hello"),
98                  $cgi->h1("Hello $who!"),
99                  $cgi->end_html;
100        }
101
102        }
103
104        # start the server on port 8080
105        my $pid = MyWebServer->new(8080)->background();
106        print "Use 'kill $pid' to stop server.\n";
107

METHODS

109   HTTP::Server::Simple->new($port, $family)
110       API call to start a new server.  Does not actually start listening
111       until you call "->run()".  If omitted, $port defaults to 8080, and
112       $family defaults to Socket::AF_INET.  The alternative domain is
113       Socket::AF_INET6.
114
115   lookup_localhost
116       Looks up the local host's IP address, and returns it.  For most hosts,
117       this is 127.0.0.1, or possibly "::1".
118
119   port [NUMBER]
120       Takes an optional port number for this server to listen on.
121
122       Returns this server's port. (Defaults to 8080)
123
124   family [NUMBER]
125       Takes an optional address family for this server to use.  Valid values
126       are Socket::AF_INET and Socket::AF_INET6.  All other values are
127       silently changed into Socket::AF_INET for backwards compatibility with
128       previous versions of the module.
129
130       Returns the address family of the present listening socket.  (Defaults
131       to Socket::AF_INET.)
132
133   host [address]
134       Takes an optional host address for this server to bind to.
135
136       Returns this server's bound address (if any).  Defaults to "undef"
137       (bind to all interfaces).
138
139   background [ARGUMENTS]
140       Runs the server in the background, and returns the process ID of the
141       started process.  Any arguments will be passed through to "run".
142
143   run [ARGUMENTS]
144       Run the server.  If all goes well, this won't ever return, but it will
145       start listening for "HTTP" requests.  Any arguments passed to this will
146       be passed on to the underlying Net::Server implementation, if one is
147       used (see "net_server").
148
149   net_server
150       User-overridable method. If you set it to a Net::Server subclass, that
151       subclass is used for the "run" method.  Otherwise, a minimal
152       implementation is used as default.
153
154   restart
155       Restarts the server. Usually called by a HUP signal, not directly.
156
157   stdio_handle [FILEHANDLE]
158       When called with an argument, sets the socket to the server to that
159       arg.
160
161       Returns the socket to the server; you should only use this for actual
162       socket-related calls like "getsockname".  If all you want is to read or
163       write to the socket, you should use "stdin_handle" and "stdout_handle"
164       to get the in and out filehandles explicitly.
165
166   stdin_handle
167       Returns a filehandle used for input from the client.  By default,
168       returns whatever was set with "stdio_handle", but a subclass could do
169       something interesting here.
170
171   stdout_handle
172       Returns a filehandle used for output to the client.  By default,
173       returns whatever was set with "stdio_handle", but a subclass could do
174       something interesting here.
175

IMPORTANT SUB-CLASS METHODS

177       A selection of these methods should be provided by sub-classes of this
178       module.
179
180   handler
181       This method is called after setup, with no parameters.  It should print
182       a valid, full HTTP response to the default selected filehandle.
183
184   setup(name => $value, ...)
185       This method is called with a name => value list of various things to do
186       with the request.  This list is given below.
187
188       The default setup handler simply tries to call methods with the names
189       of keys of this list.
190
191         ITEM/METHOD   Set to                Example
192         -----------  ------------------    ------------------------
193         method       Request Method        "GET", "POST", "HEAD"
194         protocol     HTTP version          "HTTP/1.1"
195         request_uri  Complete Request URI  "/foobar/baz?foo=bar"
196         path         Path part of URI      "/foobar/baz"
197         query_string Query String          undef, "foo=bar"
198         port         Received Port         80, 8080
199         peername     Remote name           "200.2.4.5", "foo.com"
200         peeraddr     Remote address        "200.2.4.5", "::1"
201         peerport     Remote port           42424
202         localname    Local interface       "localhost", "myhost.com"
203
204   headers([Header => $value, ...])
205       Receives HTTP headers and does something useful with them.  This is
206       called by the default "setup()" method.
207
208       You have lots of options when it comes to how you receive headers.
209
210       You can, if you really want, define "parse_headers()" and parse them
211       raw yourself.
212
213       Secondly, you can intercept them very slightly cooked via the "setup()"
214       method, above.
215
216       Thirdly, you can leave the "setup()" header as-is (or calling the
217       superclass "setup()" for unknown request items).  Then you can define
218       "headers()" in your sub-class and receive them all at once.
219
220       Finally, you can define handlers to receive individual HTTP headers.
221       This can be useful for very simple SOAP servers (to name a crack-fueled
222       standard that defines its own special HTTP headers).
223
224       To do so, you'll want to define the "header()" method in your subclass.
225       That method will be handed a (key,value) pair of the header name and
226       the value.
227
228   accept_hook
229       If defined by a sub-class, this method is called directly after an
230       accept happens.  An accept_hook to add SSL support might look like
231       this:
232
233           sub accept_hook {
234               my $self = shift;
235               my $fh   = $self->stdio_handle;
236
237               $self->SUPER::accept_hook(@_);
238
239               my $newfh =
240               IO::Socket::SSL->start_SSL( $fh,
241                   SSL_server    => 1,
242                   SSL_use_cert  => 1,
243                   SSL_cert_file => 'myserver.crt',
244                   SSL_key_file  => 'myserver.key',
245               )
246               or warn "problem setting up SSL socket: " . IO::Socket::SSL::errstr();
247
248               $self->stdio_handle($newfh) if $newfh;
249           }
250
251   post_setup_hook
252       If defined by a sub-class, this method is called after all setup has
253       finished, before the handler method.
254
255   print_banner
256       This routine prints a banner before the server request-handling loop
257       starts.
258
259       Methods below this point are probably not terribly useful to define
260       yourself in subclasses.
261
262   parse_request
263       Parse the HTTP request line.  Returns three values, the request method,
264       request URI and the protocol.
265
266   parse_headers
267       Parses incoming HTTP headers from STDIN, and returns an arrayref of
268       "(header => value)" pairs.  See "headers" for possibilities on how to
269       inspect headers.
270
271   setup_listener
272       This routine binds the server to a port and interface.
273
274   after_setup_listener
275       This method is called immediately after setup_listener. It's here just
276       for you to override.
277
278   bad_request
279       This method should print a valid HTTP response that says that the
280       request was invalid.
281
282   valid_http_method($method)
283       Given a candidate HTTP method in $method, determine if it is valid.
284       Override if, for example, you'd like to do some WebDAV.  The default
285       implementation only accepts "GET", "POST", "HEAD", "PUT", "PATCH",
286       "DELETE" and "OPTIONS".
287

AUTHOR

289       Best Practical Solutions, LLC <modules@bestpractical.com>
290

CONTRIBUTORS

292       Jesse Vincent, <jesse@bestpractical.com>. Original author.
293
294       Marcus Ramberg <drave@thefeed.no> contributed tests, cleanup, etc
295
296       Sam Vilain, <samv@cpan.org> contributed the CGI.pm split-out and
297       header/setup API.
298
299       Example section by almut on perlmonks, suggested by Mark Fuller.
300

BUGS

302       There certainly are some. Please report them via rt.cpan.org
303

LICENSE

305       This software is Copyright (c) 2004-2015 Best Practical Solutions
306
307       This library is free software; you can redistribute it and/or modify it
308       under the same terms as Perl itself.
309
310
311
312perl v5.30.1                      2020-01-30           HTTP::Server::Simple(3)
Impressum