From c50224781e3043bed783beb7f92daf852ebe253f Mon Sep 17 00:00:00 2001 From: y_uuki Date: Wed, 15 Jun 2016 20:49:07 +0900 Subject: [PATCH] Add perl simplehttp --- perl/simplehttp/lib/Simple/HTTP.pm | 65 ++++++++++++++++++++++++++++++ perl/simplehttp/main.pl | 16 ++++++++ 2 files changed, 81 insertions(+) create mode 100644 perl/simplehttp/lib/Simple/HTTP.pm create mode 100755 perl/simplehttp/main.pl diff --git a/perl/simplehttp/lib/Simple/HTTP.pm b/perl/simplehttp/lib/Simple/HTTP.pm new file mode 100644 index 0000000..f2e39ae --- /dev/null +++ b/perl/simplehttp/lib/Simple/HTTP.pm @@ -0,0 +1,65 @@ +package Simple::HTTP; +use strict; +use warnings; +use utf8; + +use POSIX qw(EINTR); +use IO::Socket::INET; +use Socket qw(IPPROTO_TCP TCP_NODELAY); + +sub infolog { + my ($format, @opts) = @_; + print sprintf($format, @opts); +} + +sub errlog { + my ($format, @opts) = @_; + print STDERR sprintf($format, @opts); +} + +sub handle_connection { + my ($conn) = @_; + + my $data; + $conn->recv($data, 1024); + $conn->send("HTTP/1.0 200 OK\n"); +} + +sub run { + my ($host, $port) = @_; + + infolog("--> listening to %s:%d\n", $host, $port); + + my $listen = IO::Socket::INET->new( + Listen => SOMAXCONN, + LocalPort => $port, + LocalAddr => $host, + Proto => 'tcp', + ReuseAddr => 1, + ); + + while (1) { + if (my ($conn, $peer) = $listen->accept) { + infolog("."); + my ($peerport, $peerhost) = unpack_sockaddr_in $peer; + my $peeraddr = inet_ntoa($peerhost); + + my $pid = fork; + unless (defined $pid) { + errlog("fork failed:$!"); + next; + } + unless ($pid) { + # child process + $listen->close; + handle_connection($conn); + $conn->close; + exit(0); + } + + $conn->close; + } + } +} + +1; diff --git a/perl/simplehttp/main.pl b/perl/simplehttp/main.pl new file mode 100755 index 0000000..fbdb940 --- /dev/null +++ b/perl/simplehttp/main.pl @@ -0,0 +1,16 @@ +#!/usr/bin/perl +use strict; +use warnings; +use utf8; + +use Getopt::Long; + +use Simple::HTTP; + +my ($host, $port) = ('127.0.0.1', '10020'); +GetOptions( + 'h=s' => \$host, + 'p=s' => \$port, +) or die; + +Simple::HTTP::run($host, $port);