Http Client in Erlang

Here’s the translation of the Go HTTP client example to Erlang, formatted in Markdown for Hugo:

Our example demonstrates how to create a simple HTTP client in Erlang. We’ll use the httpc module from the inets application to make HTTP requests.

-module(http_client).
-export([main/0]).

main() ->
    % Start the inets application
    application:ensure_all_started(inets),
    application:ensure_all_started(ssl),

    % Issue an HTTP GET request to a server
    case httpc:request(get, {"https://example.com", []}, [], []) of
        {ok, {{_, StatusCode, ReasonPhrase}, _, Body}} ->
            % Print the HTTP response status
            io:format("Response status: ~p ~s~n", [StatusCode, ReasonPhrase]),

            % Print the first 5 lines of the response body
            Lines = string:split(Body, "\n", all),
            lists:foreach(fun(Line) ->
                io:format("~s~n", [Line])
            end, lists:sublist(Lines, 1, 5));
        {error, Reason} ->
            io:format("Error: ~p~n", [Reason])
    end.

To run the program, save it as http_client.erl and use the Erlang shell:

$ erl
1> c(http_client).
{ok,http_client}
2> http_client:main().
Response status: 200 "OK"
<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />

Let’s break down the code:

  1. We define a module http_client with a main/0 function.

  2. We start the inets and ssl applications, which are required for making HTTP requests.

  3. We use httpc:request/4 to make an HTTP GET request to “https://example.com”.

  4. If the request is successful, we pattern match on the response to extract the status code, reason phrase, and body.

  5. We print the response status using io:format/2.

  6. To print the first 5 lines of the response body, we split the body into lines, then use lists:sublist/3 to get the first 5 lines, and lists:foreach/2 to print each line.

  7. If there’s an error, we print the error reason.

This example demonstrates basic HTTP client functionality in Erlang, including making a request, handling the response, and processing the response body.