Http Server in Erlang

Here’s the translation of the HTTP Server example from Go to Erlang:

Our HTTP server example demonstrates how to create a basic server using Erlang’s built-in inets application, which provides HTTP server functionality.

-module(http_server).
-export([start/0]).

start() ->
    inets:start(),
    {ok, _} = inets:start(httpd, [
        {port, 8090},
        {server_name, "erlang_http_server"},
        {server_root, "."},
        {document_root, "."},
        {modules, [
            mod_alias,
            mod_auth,
            mod_esi,
            mod_actions,
            mod_cgi,
            mod_dir,
            mod_get,
            mod_head,
            mod_log,
            mod_disk_log
        ]},
        {erl_script_alias, {"/erl", [http_server]}},
        {error_log, "error.log"},
        {security_log, "security.log"},
        {transfer_log, "transfer.log"}
    ]),
    io:format("HTTP server started on port 8090~n").

hello(SessionID, _Env, _Input) ->
    mod_esi:deliver(SessionID, "hello\n").

headers(SessionID, Env, _Input) ->
    Headers = proplists:get_value(http_headers, Env, []),
    Response = lists:foldl(fun({Key, Value}, Acc) ->
        Acc ++ io_lib:format("~s: ~s~n", [Key, Value])
    end, "", Headers),
    mod_esi:deliver(SessionID, Response).

In Erlang, we use the inets application to create an HTTP server. The concept of handlers in Erlang is implemented using modules and functions that process HTTP requests.

The start/0 function initializes the server with various configuration options, including the port number and the modules to be used for processing requests.

We define two handler functions: hello/3 and headers/3. These functions take three arguments: SessionID, Env (environment variables), and Input (request body).

The hello/3 function simply responds with “hello\n”, similar to the Go example.

The headers/3 function retrieves the HTTP headers from the Env proplist and formats them as a string to be sent back in the response.

To run the server:

$ erl -pa .
1> c(http_server).
{ok,http_server}
2> http_server:start().
HTTP server started on port 8090
ok

To test the server, you can use curl in another terminal:

$ curl localhost:8090/erl/http_server:hello
hello

$ curl localhost:8090/erl/http_server:headers
User-Agent: curl/7.64.1
Host: localhost:8090
Accept: */*

This Erlang implementation provides similar functionality to the Go example, setting up an HTTP server with two routes that handle different types of requests.