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 https://github.com/teamon/tesla library which is pretty nice for creating an abstraction/module for your different requests etc…

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New

We're in Beta

About us Mission Statement