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

IMPORTANT SUB-CLASS METHODS

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

AUTHOR

277       Copyright (c) 2004-2008 Jesse Vincent, <jesse@bestpractical.com>.  All
278       rights reserved.
279
280       Marcus Ramberg <drave@thefeed.no> contributed tests, cleanup, etc
281
282       Sam Vilain, <samv@cpan.org> contributed the CGI.pm split-out and
283       header/setup API.
284
285       Example section by almut on perlmonks, suggested by Mark Fuller.
286

BUGS

288       There certainly are some. Please report them via rt.cpan.org
289

LICENSE

291       This library is free software; you can redistribute it and/or modify it
292       under the same terms as Perl itself.
293
294
295
296perl v5.12.3                      2011-04-04           HTTP::Server::Simple(3)
Impressum