A Minimal Perl Web Server

If you want to build a full-featured HTTP server, you have some work to do. The core of the Apache web server has over 50,000 lines of code, and optional processing modules make that number much bigger.

All this software is needed to support HTTP/1.1 features: rich resource support, virtual hosting, access control, logging, configuration, monitoring, and performance features. That said, you can create a minimally functional HTTP server in under 30 lines of Perl. Let’s take a look.

Example 5-1 shows a tiny Perl program called type-o-serve. This program is a useful diagnostic tool for testing interactions with clients and proxies. Like any web server, type-o-serve waits for an HTTP connection. As soon as type-o-serve gets the request message, it prints the message on the screen; then it waits for you to type (or paste) in a response message, which is sent back to the client. This way, type-o-serve pretends to be a web server, records the exact HTTP request messages, and allows you to send back any HTTP response message.

This simple type-o-serve utility doesn’t implement most HTTP functionality, but it is a useful tool to generate server response messages the same way you can use Telnet to generate client request messages (refer back to Example 5-1). You can download the type-o-serve program from http://www.http-guide.com/tools/type-o-serve.pl.

Example 5-1. type-o-serve—a minimal Perl web server used for HTTP debugging

#!/usr/bin/perl use Socket; use Carp; ...

Get HTTP: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.