Skip to content

Instantly share code, notes, and snippets.

@yujiorama
Created May 3, 2022 06:00
Show Gist options
  • Save yujiorama/ff583edfd3a772dedc9c8faa29a81203 to your computer and use it in GitHub Desktop.
Save yujiorama/ff583edfd3a772dedc9c8faa29a81203 to your computer and use it in GitHub Desktop.
perl hello world http server
# via A Minimal Perl Web Server
# https://flylib.com/books/en/1.2.1.48/1/
#
use strict;
use warnings;
use utf8;
use feature qw/say/;
use sigtrap qw/die untrapped normal-signals/;
use Carp;
use FileHandle;
use Socket;
my $port = (@ARGV ? $ARGV[0] : 8080);
my $proto = getprotobyname('tcp');
socket(S, PF_INET, SOCK_STREAM, $proto) or die;
setsockopt(S, SOL_SOCKET, SO_REUSEADDR, pack("l", 1)) or die;
bind(S, sockaddr_in($port, INADDR_ANY)) or die;
listen(S, SOMAXCONN) or die;
say sprintf(" <<<Type-O-Serve Accepting on Port %d>>>", $port);
while (1) {
my $caddr = accept(C, S);
C->autoflush(1);
my $body = "hello world";
my $header = [
"HTTP/1.0 200 OK",
"Server: Type-0-Serve",
"Content-Type: text/plain",
"Content-Length: " . (length($body) + 4),
"",
];
my $res = [
@$header,
"",
$body,
"",
];
print C join("\r\n", @$res);
close(C);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment