#!/usr/bin/env perl use strict; use warnings; use Getopt::Long; ######################## # Command Line Options ######################## my %opts = ( port => 8080, host => 'localhost', bg => 0 ); GetOptions( "port|p=s" => \$opts{port}, "host|H=s" => \$opts{host}, "background|b" => \$opts{bg}, "help|h" => \$opts{help}, "include|I=s" => \$opts{include}, ) || ( $opts{help} = 1 ); die_with_usage() if $opts{help}; $opts{ra_class} = shift || die_with_usage("No class given"); ######################### # Setup the Environment ######################### extend_INC( $opts{include} ); load_class( $opts{ra_class} ); ###################### # Run the Web Server ###################### my $server = WebServer->new( $opts{port} ); $server->host( $opts{host} ); my $run_method = $opts{bg} ? "background" : "run"; $server->{ra_class} = $opts{ra_class}; $server->$run_method(); exit; ########### # Helpers ########### sub extend_INC { my $include = shift || ""; my @dirs = split /,/, $include; unshift @INC, reverse(@dirs); } sub load_class { my $klass = shift; eval "require $klass;"; die "Unable to load $klass: $@\n" if $@; } sub die_with_usage { my $msg = shift || ""; warn "$msg\n\n" if $msg; die <{ra_class}; my $ra = $klass->new(); $ra->run(); } sub print_banner { my $self = shift; print "Server is serving class " . $self->{ra_class} . " at http://" . $self->host . ":" . $self->port . "/\n\n"; } 1; package HTTP::Server::Simple; use strict; use warnings; use FileHandle; use Socket; use Carp; use URI::Escape; no warnings 'redefine'; use vars qw($VERSION $bad_request_doc); $VERSION = '0.26'; =head1 NAME HTTP::Server::Simple - Lightweight HTTP server =head1 SYNOPSIS use warnings; use strict; use HTTP::Server::Simple; my $server = HTTP::Server::Simple->new(); $server->run(); However, normally you will sub-class the HTTP::Server::Simple::CGI module (see L); 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; =head1 DESCRIPTION This is a simple standalone HTTP server. By default, it doesn't thread or fork. It does, however, act as a simple frontend which can be used to build a standalone web-based application or turn a CGI into one. (It's possible to use Net::Server to get threading, forking, preforking and so on. Autrijus Tang wrote the functionality and owes docs for that ;) By default, the server traps a few signals: =over =item HUP When you C the server, it does its best to rexec itself. Please note that in order to provide restart-on-SIGHUP, HTTP::Server::Simple sets 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. by "kill -HUP