Wednesday, October 15, 2008

Nano HTTP server

A tiny utility that provides a super-minimalist HTTP server, serving up contents of just one file. I mocked it up in Perl a while back, I think it was supposed to provide a WAR file for remote deployment to Tomcat, or some such.

Not really that great, but may be useful for quick-and-dirty file transfer or for testing HTTP stuff. The source code follows:
# listens for HTTP connections and, regardless of request,
# always returns contents of given file, with given content-type
# header value
# useful to serve up some test data as though it was from a real
# HTTP server

use IO::Socket;

my($port, $file, $contentType) = @ARGV;

$port = int($port);

defined $contentType or die "must supply content type";

open(FILE, $file) or die "cannot open file";
local $/ = undef;
my $data = <FILE>;

my $socket = new IO::Socket::INET('LocalPort' => $port, 'Proto' => 'tcp', 'Listen' => 1, 'Reuse' => 1);
$socket or die "cannot create listener socket";

my $clientSocket = $socket->accept();

# read a token amount of data, just for appearance's sake
my $buf;
$clientSocket->recv($buf, 5);

# print our response
print $clientSocket "HTTP/1.0 200 OK\r\n";
print $clientSocket "Content-Type: ", $contentType, "\r\n";
print $clientSocket "Content-Length: ", length($data), "\r\n";
print $clientSocket "\r\n";
print $clientSocket $data;


No comments: