1Net::Server::HTTP(3)  User Contributed Perl Documentation Net::Server::HTTP(3)
2
3
4

NAME

6       Net::Server::HTTP - very basic Net::Server based HTTP server class
7

TEST ONE LINER

9           perl -e 'use base qw(Net::Server::HTTP); main->run(port => 8080)'
10           # will start up an echo server
11

SYNOPSIS

13           use base qw(Net::Server::HTTP);
14           __PACKAGE__->run;
15
16           sub process_http_request {
17               my $self = shift;
18
19               print "Content-type: text/html\n\n";
20               print "<form method=post action=/bam><input type=text name=foo><input type=submit></form>\n";
21
22               require Data::Dumper;
23               local $Data::Dumper::Sortkeys = 1;
24
25               require CGI;
26               my $form = {};
27               my $q = CGI->new; $form->{$_} = $q->param($_) for $q->param;
28
29               print "<pre>".Data::Dumper->Dump([\%ENV, $form], ['*ENV', 'form'])."</pre>";
30           }
31

DESCRIPTION

33       Even though Net::Server::HTTP doesn't fall into the normal parallel of
34       the other Net::Server flavors, handling HTTP requests is an often
35       requested feature and is a standard and simple protocol.
36
37       Net::Server::HTTP begins with base type MultiType defaulting to
38       Net::Server::Fork.  It is easy to change it to any of the other
39       Net::Server flavors by passing server_type => $other_flavor in the
40       server configurtation.  The port has also been defaulted to port 80 -
41       but could easily be changed to another through the server
42       configuration.  You can also very easily add ssl by including,
43       proto=>"ssl" and provide a SSL_cert_file and SSL_key_file.
44
45       For example, here is a basic server that will bind to all interfaces,
46       will speak both HTTP on port 8080 as well as HTTPS on 8443, and will
47       speak both IPv4, as well as IPv6 if it is available.
48
49           use base qw(Net::Server::HTTP);
50
51           __PACKAGE__->run(
52               port  => [8080, "8443/ssl"],
53               ipv   => '*', # IPv6 if available
54               SSL_key_file  => '/my/key',
55               SSL_cert_file => '/my/cert',
56           );
57

METHODS

59       "_init_access_log"
60           Used to open and initialize any requested access_log (see
61           access_log_file and access_log_format).
62
63       "_tie_client_stdout"
64           Used to initialize automatic response header parsing.
65
66       "process_http_request"
67           Will be passed the client handle, and will have STDOUT and STDIN
68           tied to the client.
69
70           During this method, the %ENV will have been set to a standard CGI
71           style environment.  You will need to be sure to print the Content-
72           type header.  This is one change from the other standard
73           Net::Server base classes.
74
75           During this method you can read from %ENV and STDIN just like a
76           normal HTTP request in other web servers.  You can print to STDOUT
77           and Net::Server will handle the header negotiation for you.
78
79           Note: Net::Server::HTTP has no concept of document root or script
80           aliases or default handling of static content.  That is up to the
81           consumer of Net::Server::HTTP to work out.
82
83           Net::Server::HTTP comes with a basic %ENV display installed as the
84           default process_http_request method.
85
86       "process_request"
87           This method has been overridden in Net::Server::HTTP - you should
88           not use it while using Net::Server::HTTP.  This overridden method
89           parses the environment and sets up request alarms and handles dying
90           failures.  It calls process_http_request once the request is ready
91           and headers have been parsed.
92
93       "process_headers"
94           Used to read in the incoming headers and set the ENV.
95
96       "_init_http_request_info"
97           Called at the end of process_headers.  Initializes the contents of
98           http_request_info.
99
100       "http_request_info"
101           Returns a hashref of information specific to the current request.
102           This information will be used for logging later on.
103
104       "send_status"
105           Takes an HTTP status and a message.  Sends out the correct headers.
106
107       "send_500"
108           Calls send_status with 500 and the argument passed to send_500.
109
110       c<log_http_request>
111           Called at the end of post_process_request.  The default method
112           looks for the default access_log_format and checks if logging was
113           initilized during _init_access_log.  If both of these exist, the
114           http_request_info is formatted using http_log_format and the result
115           is logged.
116
117       "http_log_format"
118           Takes a format string, and request_info and returns a formatted
119           string.  The format should follow the apache mod_log_config
120           specification.  As in the mod_log_config specification,
121           backslashes, quotes should be escaped with backslashes and you may
122           also include \n and \t characters as well.
123
124           The following is a listing of the available parameters as well as
125           sample output based on a very basic HTTP server.
126
127               %%                %                 # a percent
128               %a                ::1               # remote ip
129               %A                ::1               # local ip
130               %b                83                # response size (- if 0) Common Log Format
131               %B                83                # response size
132               %{bar}C           baz               # value of cookie by that name
133               %D                916               # elapsed in microseconds
134               %{HTTP_COOKIE}e   bar=baz           # value of %ENV by that name
135               %f                -                 # filename - unused
136               %h                ::1               # remote host if lookups are on, remote ip otherwise
137               %H                http              # request protocol
138               %{Host}i          localhost:8080    # request header by that name
139               %I                336               # bytes received including headers
140               %l                -                 # remote logname - unsused
141               %m                GET               # request method
142               %n                Just a note       # http_note by that name
143               %{Content-type}o  text/html         # output header by that name
144               %O                189               # response size including headers
145               %p                8080              # server port
146               %P                22999             # pid - does not support %{tid}P
147               q                 ?hello=there      # query_string including ? (- otherwise)
148               r                 GET /bam?hello=there HTTP/1.1      # the first line of the request
149               %s                200               # response status
150               %u                -                 # remote user - unused
151               %U                /bam              # request path (no query string)
152               %t                [06/Jun/2012:12:14:21 -0600]       # http_log_time standard format
153               %t{%F %T %z}t     [2012-06-06 12:14:21 -0600]        # http_log_time with format
154               %T                0                 # elapsed time in seconds
155               %v                localhost:8080    # http_log_vhost - partial implementation
156               %V                localhost:8080    # http_log_vhost - partial implementation
157               %X                -                 # Connection completed and is 'close' (-)
158
159           Additionally, the log parsing allows for the following formats.
160
161               %>s               200               # status of last request
162               %<s               200               # status of original request
163               %400a             -                 # remote ip if status is 400
164               %!400a            ::1               # remote ip if status is not 400
165               %!200a            -                 # remote ip if status is not 200
166
167           There are few bits not completely implemented:
168
169               > and <    # There is no internal redirection
170               %I         # The answer to this is based on header size and Content-length
171                            instead of the more correct actual number of bytes read though
172                            in common cases those would be the same.
173               %X         # There is no Connection keepalive in the default server.
174               %v and %V  # There are no virtual hosts in the default HTTP server.
175               %{tid}P    # The default servers are not threaded.
176
177           See the "access_log_format" option for how to set a different
178           format as well as to see the default string.
179
180       "exec_cgi"
181           Allow for calling an external script as a CGI.  This will use
182           IPC::Open3 to fork a new process and read/write from it.
183
184               use base qw(Net::Server::HTTP);
185               __PACKAGE__->run;
186
187               sub process_http_request {
188                   my $self = shift;
189
190                   if ($ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} =~ s{^ (/foo) (?= $ | /) }{}x) {
191                      $ENV{'SCRIPT_NAME'} = $1;
192                      my $file = "/var/www/cgi-bin/foo"; # assuming this exists
193                      return $self->exec_cgi($file);
194                   }
195
196                   print "Content-type: text/html\n\n";
197                   print "<a href=/foo>Foo</a>";
198               }
199
200           At this first release, the parent server is not tracking the child
201           script which may cause issues if the script is running when a HUP
202           is received.
203
204       "http_log_time"
205           Used to implement the %t format.
206
207       "http_log_env"
208           Used to implement the %e format.
209
210       "http_log_cookie"
211           Used to implement the %C format.
212
213       "http_log_header_in"
214           used to implement the %i format.
215
216       "http_log_note"
217           Used to implement the %n format.
218
219       "http_note"
220           Takes a key and an optional value.  If passed a key and value, sets
221           the note for that key.  Always returns the value.  These notes
222           currently only are used for %{key}n output format.
223
224       "http_log_header_out"
225           Used to implement the %o format.
226
227       "http_log_pid"
228           Used to implement the %P format.
229
230       "http_log_vhost"
231           Used to implement the %v and %V formats.
232
233       "http_log_constat"
234           Used to implement the %X format.
235
236       "exec_trusted_perl"
237           Allow for calling an external perl script.  This method will still
238           fork, but instead of using IPC::Open3, it simply requires the perl
239           script.  That means that the running script will be able to make
240           use of any shared memory.  It also means that the
241           STDIN/STDOUT/STDERR handles the script is using are those directly
242           bound by the server process.
243
244               use base qw(Net::Server::HTTP);
245               __PACKAGE__->run;
246
247               sub process_http_request {
248                   my $self = shift;
249
250                   if ($ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} =~ s{^ (/foo) (?= $ | /) }{}x) {
251                      $ENV{'SCRIPT_NAME'} = $1;
252                      my $file = "/var/www/cgi-bin/foo"; # assuming this exists
253                      return $self->exec_trusted_perl($file);
254                   }
255
256                   print "Content-type: text/html\n\n";
257                   print "<a href=/foo>Foo</a>";
258               }
259
260           At this first release, the parent server is not tracking the child
261           script which may cause issues if the script is running when a HUP
262           is received.
263
264       "exec_fork_hook"
265           This method is called after the fork of exec_trusted_perl and
266           exec_cgi hooks.  It is passed the pid (0 if the child) and the file
267           being ran.  Note, that the hook will not be called from the child
268           during exec_cgi.
269
270       "http_dispatch"
271           Called if the default process_http_request and process_request
272           methods have not been overridden and "app" configuration parameters
273           have been passed.  In this case this replaces the default echo
274           server.  You can also enable this subsystem for your own direct use
275           by setting enable_dispatch to true during configuration.  See the
276           "app" configuration item.  It will be passed a dispatch qr (regular
277           expression) generated during _check_dispatch, and a dispatch table.
278           The qr will be applied to path_info.  This mechanism could be used
279           to augment Net::Server::HTTP with document root and virtual host
280           capabilities.
281

OPTIONS

283       In addition to the command line arguments of the Net::Server base
284       classes you can also set the following options.
285
286       max_header_size
287           Defaults to 100_000.  Maximum number of bytes to read while parsing
288           headers.
289
290       server_revision
291           Defaults to Net::Server::HTTP/$Net::Server::VERSION.
292
293       timeout_header
294           Defaults to 15 - number of seconds to wait for parsing headers.
295
296       timeout_idle
297           Defaults to 60 - number of seconds a request can be idle before the
298           request is closed.
299
300       access_log_file
301           Defaults to undef.  If true, this represents the location of where
302           the access log should be written to.  If a special value of STDERR
303           is passed, the access log entry will be writing to the same
304           location as the ERROR log.
305
306       access_log_format
307           Should be a valid apache log format that will be passed to
308           http_log_format.  See the http_log_format method for more
309           information.
310
311           The default value is the NCSA extended/combined log format:
312
313               '%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"'
314
315       app Takes one or more items and registers them for dispatch.  Arguments
316           may be supplied as an arrayref containing a location/target pairs,
317           a hashref containing a location/target pairs, a bare code ref that
318           will use "/" as the location and the codref as the target, a string
319           with a space indicating "location target", a string containing
320           "location=target", or finally a string that will be used as both
321           location and target.  For items passed as an arrayref or hashref,
322           the target may be a coderef which will be called and should handle
323           the request.  In all other cases the target should be a valid
324           executable suitable for passing to exec_cgi.
325
326           The locations will be added in the order that they are configured.
327           They will be added to a regular expression which will be applied to
328           the incoming PATH_INFO string.  If the match is successful, the
329           $ENV{'SCRIPT_NAME'} will be set to the matched portion and the
330           matched portion will be removed from $ENV{'PATH_INFO'}.
331
332           Once an app has been passed, it is necessary for the server to
333           listen on /.  Therefore if "/" has not been specifically configured
334           for dispatch, the first found dispatch target will also be used to
335           handle "/".
336
337           For convenience, if the log_level is 2 or greater, the dispatch
338           table is output to the log.
339
340           This mechanism is left as a generic mechanism suitable for
341           overriding by servers meant to handle more complex dispatch.  At
342           the moment there is no handling of virtual hosts.  At some point we
343           will add in the default ability to play static content and likely
344           for the ability to configure virtual hosts - or that may have to
345           wait for a third party module.
346
347               app => "/home/paul/foo.cgi",
348                 # Dispatch: /home/paul/foo.cgi => home/paul/foo.cgi
349                 # Dispatch: / => home/paul/foo.cgi (default)
350
351
352               app => "../../foo.cgi",
353               app => "./bar.cgi",
354               app => "baz ./bar.cgi",
355               app => "bim=./bar.cgi",
356                 # Dispatch: /foo.cgi => ../../foo.cgi
357                 # Dispatch: /bar.cgi => ./bar.cgi
358                 # Dispatch: /baz => ./bar.cgi
359                 # Dispatch: /bim => ./bar.cgi
360                 # Dispatch: / => ../../foo.cgi (default)
361
362
363               app => "../../foo.cgi",
364               app => "/=./bar.cgi",
365                 # Dispatch: /foo.cgi => ../../foo.cgi
366                 # Dispatch: / => ./bar.cgi
367
368               # you could also do this on the commandline
369               net-server HTTP app ../../foo.cgi app /=./bar.cgi
370
371               # extended options when configured from code
372
373               Net::Server::HTTP->run(app => { # loses order of matching
374                 '/' => sub { ... },
375                 '/foo' => sub { ... },
376                 '/bar' => '/path/to/some.cgi',
377               });
378
379               Net::Server::HTTP->run(app => [
380                 '/' => sub { ... },
381                 '/foo' => sub { ... },
382                 '/bar' => '/path/to/some.cgi',
383               ]);
384

TODO

386       Add support for writing out HTTP/1.1.
387

AUTHOR

389       Paul T. Seamons paul@seamons.com
390

THANKS

392       See Net::Server
393

SEE ALSO

395       Please see also Net::Server::Fork, Net::Server::INET,
396       Net::Server::PreFork, Net::Server::PreForkSimple,
397       Net::Server::MultiType, Net::Server::Single Net::Server::SIG
398       Net::Server::Daemonize Net::Server::Proto
399
400
401
402perl v5.26.3                      2017-08-10              Net::Server::HTTP(3)
Impressum