Http Client in Elixir

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

Our example will demonstrate how to make simple HTTP requests using Elixir. The Elixir standard library provides excellent support for HTTP clients through the HTTPoison library.

defmodule HttpClient do
  def main do
    # Issue an HTTP GET request to a server. HTTPoison.get! is a convenient
    # function that makes the request and raises an exception if there's an error.
    response = HTTPoison.get!("https://elixir-lang.org")

    # Print the HTTP response status.
    IO.puts("Response status: #{response.status_code}")

    # Print the first 5 lines of the response body.
    response.body
    |> String.split("\n")
    |> Enum.take(5)
    |> Enum.each(&IO.puts/1)
  end
end

To run this program, you’ll need to add HTTPoison as a dependency in your mix.exs file:

defp deps do
  [
    {:httpoison, "~> 1.8"}
  ]
end

Then, run the following commands:

$ mix deps.get
$ mix run -e "HttpClient.main()"
Response status: 200
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

In this Elixir version:

  1. We define a module HttpClient with a main function.
  2. We use HTTPoison.get! to make a GET request. This function will raise an exception if there’s an error, similar to how the Go version uses panic.
  3. We print the response status code using IO.puts.
  4. To print the first 5 lines of the response body, we split the body into lines, take the first 5, and print each one.
  5. Elixir’s pipe operator (|>) is used to chain these operations together in a readable way.

Note that Elixir doesn’t have a concept of “defer” as in Go. Resource cleanup in Elixir is typically handled through other means, such as the use of with statements or try/rescue blocks when necessary.

This example demonstrates basic HTTP client functionality in Elixir, showcasing how to make requests and process responses in a straightforward manner.