Http Server in Perl

Here’s the translation of the HTTP Server example from Go to Perl, formatted as Markdown suitable for Hugo:

Writing a basic HTTP server is easy using the `HTTP::Server::Simple` module in Perl.

```perl
use strict;
use warnings;
use HTTP::Server::Simple::CGI;
use base qw(HTTP::Server::Simple::CGI);

# A fundamental concept in HTTP servers is handlers. In Perl, we can define
# our handlers as methods in our server class.

sub handle_GET {
    my ($self, $cgi) = @_;
    my $path = $cgi->path_info();

    if ($path eq '/hello') {
        print "HTTP/1.0 200 OK\r\n";
        print $cgi->header('text/plain');
        print "hello\n";
    } 
    elsif ($path eq '/headers') {
        print "HTTP/1.0 200 OK\r\n";
        print $cgi->header('text/plain');
        
        # This handler does something a little more sophisticated by reading 
        # all the HTTP request headers and echoing them into the response body.
        foreach my $header ($cgi->http()) {
            print "$header: ", $cgi->http($header), "\n";
        }
    } 
    else {
        print "HTTP/1.0 404 Not Found\r\n";
        print $cgi->header('text/plain');
        print "404 Not Found\n";
    }
}

# Create and run the server
my $port = 8090;
my $server = __PACKAGE__->new($port);
print "Server running at http://localhost:$port/\n";
$server->run();

In this Perl version, we’re using the HTTP::Server::Simple::CGI module to create a basic HTTP server. Here’s a breakdown of the code:

  1. We define a class that inherits from HTTP::Server::Simple::CGI.

  2. We implement a handle_GET method that acts as our request handler. This method checks the path of the request and responds accordingly.

  3. For the /hello path, we simply return “hello\n”.

  4. For the /headers path, we echo back all the request headers.

  5. We create an instance of our server class, specifying the port to listen on (8090 in this case).

  6. Finally, we call the run method to start the server.

To run the server:

$ perl http_server.pl &

You can then access the server:

$ curl localhost:8090/hello
hello

$ curl localhost:8090/headers
User-Agent: curl/7.68.0
Host: localhost:8090
Accept: */*

This Perl implementation provides similar functionality to the original example, demonstrating how to create a basic HTTP server and handle different routes.