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.
To run the program, save it as http_client.erl
and use the Erlang shell:
Let’s break down the code:
We define a module
http_client
with amain/0
function.We start the
inets
andssl
applications, which are required for making HTTP requests.We use
httpc:request/4
to make an HTTP GET request to “https://example.com”.If the request is successful, we pattern match on the response to extract the status code, reason phrase, and body.
We print the response status using
io:format/2
.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, andlists:foreach/2
to print each line.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.