lud

lud

Basic code to use mint (http client)

Hello,

I am trying to use mint to make some http requests with Elixir, and reading the docs I wrote the following code.

It works fine (for basic GET requests and everything is hardcoded, it’s normal, just a test) but it seems a bit to much to use a library.

Questions at the end of the post.

defmodule HTTP do
  @empty_state %{data: [], done: false}

  def run do
    with {:ok, conn} <- Mint.HTTP.connect(:http, "httpbin.org", 80),
         {:ok, conn, _ref} <- Mint.HTTP.request(conn, "GET", "/", [], nil) do
      handle_response(conn, @empty_state)
    end
  end

  defp handle_response(conn, state) do
    receive do
      message ->
        case Mint.HTTP.stream(conn, message) do
          {:ok, conn, responses} ->
            case Enum.reduce(responses, state, &handle_res/2) do
              # Loop ends here
              %{done: true} = state -> {:ok, state}
              %{done: false} = state -> handle_response(conn, state)
            end

          {:error, _, reason, _} ->
            {:error, reason}

          :unknown ->
            exit({:unexpected, message})
        end
    end
  end

  defp handle_res({:status, _, status}, state),
    do: Map.put(state, :status, status)

  defp handle_res({:headers, _, headers}, state),
    do: Map.put(state, :headers, headers)

  defp handle_res({:data, _, data}, state),
    do: Map.update!(state, :data, fn acc -> [data | acc] end)

  defp handle_res({:done, _}, state) do
    Map.update!(state, :data, fn acc ->
      acc
      |> :lists.reverse()
      |> Enum.join("")
    end)
    |> Map.put(:done, true)
  end
end

Task.async(fn -> HTTP.run() end)
|> Task.await()
|> case do
  {:ok, state} ->
    state
    |> Map.get(:data)
    |> IO.puts()

  other ->
    IO.inspect(other, pretty: true)
end


A quick note : I intend to use this from a GenServer, and I have no concerns about performance for this project, so to avoid handling messages, I will spawn a Task to handle the request, so I do not care about the request reference or :unknown messages. Also I know there are other responses possibles.

But again I do not expect other messages.

Questions

  • Is my code :ok ? I’ll take any remarks.
  • Am I expected to do that to use this library ?
  • Do you think mint should provide a helper like this for basic single requests ?
  • If I got it right, connect/3 is separated from request/5 for connection reuse. Can I do multiple requests with the same conn ? And if yes, should I use the conn from connect() or the last updated one ?

Thank you !

Most Liked

dimitarvp

dimitarvp

I highly recommend Tesla. It supports changing of the underlying HTTP client while providing a very sensible and convenient thin abstraction layer above them.

jola

jola

If you’re just looking to make some requests, look at HTTPoison (based on hackney) or Mojito (based on Mint).

Mint is a low level library which is pretty high effort if you’re not looking specifically for the features it offers. It explicitly doesn’t provide helpers to do requests, look at Mojito for that.

outlog

outlog

what @jola said - just wanted to add the tesla GitHub - elixir-tesla/tesla: The flexible HTTP client library for Elixir, with support for middleware and multiple adapters. · GitHub library which is pretty nice for creating an abstraction/module for your different requests etc..

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54921 245
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement