elixir-mint / mint

Functional HTTP client for Elixir with support for HTTP/1 and HTTP/2 🌱
Apache License 2.0
1.37k stars 112 forks source link

Getting returned absolutely nothing from a HTTP request #376

Closed Riven-Spell closed 1 year ago

Riven-Spell commented 1 year ago

I get the feeling I'm doing something tremendously dumb, but I just cannot figure it out for the life of me.

The following code returns the following information:

  def downloadInput({year, day}, authToken) do
    path = "/#{year}/day/#{day}/input"
    # Open a connection
    {:ok, conn} = Mint.HTTP.connect(:https, "adventofcode.com", 443, protocols: [:http2])
    # Initiate the request
    {:ok, conn, request_ref} = Mint.HTTP.request(conn, "GET", path, [], nil)

    # Grab details
    receive do
      message ->
        message |> IO.inspect()
        {:ok, conn, responses} = Mint.HTTP.stream(conn, message)

        body =
          responses
          |> IO.inspect()
          |> Enum.filter(fn
            {:data, ^request_ref, _} -> true
            _ -> false
          end)
          |> Enum.map(fn {_, _, data} -> data end)

        Mint.HTTP.close(conn)
        body
    end
  end
{:ssl,
 {:sslsocket, {:gen_tcp, #Port<0.7>, :tls_connection, :undefined},
  [#PID<0.222.0>, #PID<0.221.0>]}, <<0, 0, 0, 4, 1, 0, 0, 0, 0>>}
[]
[]

Why is nothing returned whatsoever?

whatyouhide commented 1 year ago

You need to listen to as many messages as may arrive. Your receive gets the first message on the socket, which is the adventofcode.com header exchanging some HTTP/2 protocol messages with the connection. The response is in the next message. This works:

{:ok, conn} = Mint.HTTP.connect(:https, "adventofcode.com", 443)
{:ok, conn, req_ref} = Mint.HTTP.request(conn, "GET", "/2021/day/24/input", [], nil)

msg = receive do: (msg -> msg)
{:ok, conn, []} = Mint.HTTP.stream(conn, msg)

msg = receive do: (msg -> msg)
{:ok, conn, responses} = Mint.HTTP.stream(conn, msg)
dbg(responses)

You can see examples of receiving messages recursively in the Mint documentation: https://hexdocs.pm/mint/1.4.2/architecture.html#usage-examples

whatyouhide commented 1 year ago

I added a warning to the docs for Mint.HTTP.stream/2. Hopefully it will help call out attention to this 🙃

CleanShot 2022-11-30 at 08 18 26@2x