Skip to content

Commit

Permalink
Add perl simplehttp
Browse files Browse the repository at this point in the history
  • Loading branch information
yuuki committed Jun 15, 2016
1 parent eca42db commit c502247
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
65 changes: 65 additions & 0 deletions perl/simplehttp/lib/Simple/HTTP.pm
Original file line number Diff line number Diff line change
@@ -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;
16 changes: 16 additions & 0 deletions perl/simplehttp/main.pl
Original file line number Diff line number Diff line change
@@ -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);

0 comments on commit c502247

Please sign in to comment.