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

OPTIONS

298       In addition to the command line arguments of the Net::Server base
299       classes you can also set the following options.
300
301       max_header_size
302           Defaults to 100_000.  Maximum number of bytes to read while parsing
303           headers.
304
305       server_revision
306           Defaults to Net::Server::HTTP/$Net::Server::VERSION.
307
308       timeout_header
309           Defaults to 15 - number of seconds to wait for parsing headers.
310
311       timeout_idle
312           Defaults to 60 - number of seconds a request can be idle before the
313           request is closed.
314
315       access_log_file
316           Defaults to undef.  If true, this represents the location of where
317           the access log should be written to.  If a special value of STDERR
318           or /dev/stderr is passed, the access log entry will be written to
319           the same location as the ERROR log.  If a special value of STDOUT
320           or /dev/stdout is passed, the access log entry will be written to
321           standard out.
322
323       access_log_function
324           Can take a coderef or method name to call when an log_http_request
325           method is called.  Will be passed the formatted log access log
326           message.
327
328           Note that functions depending upon stdout will not function during
329           Net::Server::HTTP process_request because stdout is always tied for
330           the client (and not restored after running).
331
332       access_log_format
333           Should be a valid apache log format that will be passed to
334           http_log_format.  See the http_log_format method for more
335           information.
336
337           The default value is the NCSA extended/combined log format:
338
339               '%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"'
340
341       app Takes one or more items and registers them for dispatch.  Arguments
342           may be supplied as an arrayref containing a location/target pairs,
343           a hashref containing a location/target pairs, a bare code ref that
344           will use "/" as the location and the codref as the target, a string
345           with a space indicating "location target", a string containing
346           "location=target", or finally a string that will be used as both
347           location and target.  For items passed as an arrayref or hashref,
348           the target may be a coderef which will be called and should handle
349           the request.  In all other cases the target should be a valid
350           executable suitable for passing to exec_cgi.
351
352           The locations will be added in the order that they are configured.
353           They will be added to a regular expression which will be applied to
354           the incoming PATH_INFO string.  If the match is successful, the
355           $ENV{'SCRIPT_NAME'} will be set to the matched portion and the
356           matched portion will be removed from $ENV{'PATH_INFO'}.
357
358           Once an app has been passed, it is necessary for the server to
359           listen on /.  Therefore if "/" has not been specifically configured
360           for dispatch, the first found dispatch target will also be used to
361           handle "/".
362
363           For convenience, if the log_level is 2 or greater, the dispatch
364           table is output to the log.
365
366           This mechanism is left as a generic mechanism suitable for
367           overriding by servers meant to handle more complex dispatch.  At
368           the moment there is no handling of virtual hosts.  At some point we
369           will add in the default ability to play static content and likely
370           for the ability to configure virtual hosts - or that may have to
371           wait for a third party module.
372
373               app => "/home/paul/foo.cgi",
374                 # Dispatch: /home/paul/foo.cgi => home/paul/foo.cgi
375                 # Dispatch: / => home/paul/foo.cgi (default)
376
377
378               app => "../../foo.cgi",
379               app => "./bar.cgi",
380               app => "baz ./bar.cgi",
381               app => "bim=./bar.cgi",
382                 # Dispatch: /foo.cgi => ../../foo.cgi
383                 # Dispatch: /bar.cgi => ./bar.cgi
384                 # Dispatch: /baz => ./bar.cgi
385                 # Dispatch: /bim => ./bar.cgi
386                 # Dispatch: / => ../../foo.cgi (default)
387
388
389               app => "../../foo.cgi",
390               app => "/=./bar.cgi",
391                 # Dispatch: /foo.cgi => ../../foo.cgi
392                 # Dispatch: / => ./bar.cgi
393
394               # you could also do this on the commandline
395               net-server HTTP app ../../foo.cgi app /=./bar.cgi
396
397               # extended options when configured from code
398
399               Net::Server::HTTP->run(app => { # loses order of matching
400                 '/' => sub { ... },
401                 '/foo' => sub { ... },
402                 '/bar' => '/path/to/some.cgi',
403               });
404
405               Net::Server::HTTP->run(app => [
406                 '/' => sub { ... },
407                 '/foo' => sub { ... },
408                 '/bar' => '/path/to/some.cgi',
409               ]);
410
411       default_content_type
412           Default is text/html.  Set on any responses that have not yet
413           passed a content-type
414
415       allow_body_on_all_statuses
416           By default content-type and printing a body are not allowed on 204,
417           304, or 1xx statuses.  Set this flag to automatically send a
418           content-type on those statuses as well.
419

TODO

421       Add support for writing out HTTP/1.1.
422

AUTHOR

424       Paul T. Seamons paul@seamons.com
425

THANKS

427       See Net::Server
428

SEE ALSO

430       Please see also Net::Server::Fork, Net::Server::INET,
431       Net::Server::PreFork, Net::Server::PreForkSimple,
432       Net::Server::MultiType, Net::Server::Single Net::Server::SIG
433       Net::Server::Daemonize Net::Server::Proto
434
435
436
437perl v5.36.0                      2023-03-17              Net::Server::HTTP(3)
Impressum