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

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
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
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
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
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
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
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
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43591 214
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
RisingFromAshes
I've read in another post that it may be possible with a router helper - but I couldn't find an appropriate one, and tbh, I'm still just ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
hariharasudhan94
Lets say i have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; "XX...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement