Improved daemon.pl example
Christian Hansen [Sun, 16 Oct 2005 14:42:47 +0000 (14:42 +0000)]
MANIFEST
examples/daemon.pl

index 275c417..6ba9f96 100644 (file)
--- a/MANIFEST
+++ b/MANIFEST
@@ -1,4 +1,6 @@
 lib/HTTP/Request/AsCGI.pm
+examples/daemon.pl
+examples/synopsis.pl
 t/01use.t
 t/04io.t
 t/05env.t
index 083afd1..5a16c89 100644 (file)
@@ -9,25 +9,33 @@ use HTTP::Request;
 use HTTP::Request::AsCGI;
 use HTTP::Response;
 
-my $server = HTTP::Daemon->new || die;
+$SIG{'PIPE'} = 'IGNORE';
+
+my $server = HTTP::Daemon->new( LocalPort => 3000, ReuseAddr => 1 ) || die;
 
 print "Please contact me at: <URL:", $server->url, ">\n";
 
 while ( my $client = $server->accept ) {
+    
+    my %e = (
+        REMOTE_ADDR => $client->peerhost,
+        REMOTE_HOST => $client->peerhost,
+        REMOTE_PORT => $client->peerport
+    );
 
     while ( my $request = $client->get_request ) {
 
-        my $c = HTTP::Request::AsCGI->new($request)->setup;
+        my $c = HTTP::Request::AsCGI->new( $request, %e )->setup;
         my $q = CGI->new;
 
-        print $q->header, 
-              $q->start_html('Hello World'), 
+        print $q->header,
+              $q->start_html('Hello World'),
               $q->h1('Hello World'),
               $q->end_html;
 
         $c->restore;
 
-        my $message = "HTTP/1.1 200 OK\x0d\x0a";
+        my $message = "HTTP/1.1 200\x0d\x0a";
 
         while ( my $line = $c->stdout->getline ) {
             $message .= $line;
@@ -35,6 +43,13 @@ while ( my $client = $server->accept ) {
         }
 
         my $response = HTTP::Response->parse($message);
+
+        if ( my $code = $response->header('Status') ) {
+            $response->code($code);
+        }
+
+        $response->header( Connection => 'close' );
+        $response->protocol( $request->protocol );
         $response->content( sub {
             if ( $c->stdout->read( my $buffer, 4096 ) ) {
                 return $buffer;
@@ -43,7 +58,8 @@ while ( my $client = $server->accept ) {
         });
 
         $client->send_response($response);
+        $client->close;
     }
 
-    $client->close;
+    #$client->close;
 }