How do i access struct variables?

I have the following code:

IO.inspect "hey!"
IO.inspect resp
IO.inspect resp.headers

I am not able to access the attribute header.
resp is of type HTTPoison.Response


https://hexdocs.pm/httpoison/HTTPoison.Response.html

is there anything that I am missing?

output:

"hey!"
    {:ok,
     %HTTPoison.Response{
       body: "",
       headers: [
         {"Server", "Apache-Coyote/1.1"},
         {"Location", "http://0.0.0.0/xyz/main.jsp"},
         {"Content-Type", "text/html"},
         {"Content-Length", "0"},
         {"Date", "Fri, 04 Jan 2019 13:00:42 GMT"}
       ],
       request: %HTTPoison.Request{
         body: "login=login&",
         headers: [
           {"Content-Type", "application/x-www-form-urlencoded"},
           {"Cookie", "JSESSIONID=A229A0234B488C2A4B9DF0"}
         ],
         method: :post,
         options: [timeout: 5000, recv_timeout: 5000],
         params: %{},
         url: "http://0.0.0.0/xyz/index.jsp"
       },
       request_url: "http://0.0.0.0/xyz/index.jsp",
       status_code: 302
     }}
    [error] GenServer #PID<0.361.0> terminating
    ** (ArgumentError) argument error
        :erlang.apply({:ok, %HTTPoison.Response{body: "", headers: [{"Server", "Apache-Coyote/1.1"}, {"Location", "http://0.0.0.0/abc/main.jsp"}, {"Content-Type", "text/html"}, {"Content-Length", "0"}, {"Date", "Fri, 04 Jan 2019 13:00:42 GMT"}], request: %HTTPoison.Request{body: "login=login&login", headers: [{"Content-Type", "application/x-www-form-urlencoded"}, {"Cookie", "JSESSIONID=A229A0234B418720D921A88C2A4B9DF0"}], method: :post, options: [timeout: 5000, recv_timeout: 5000], params: %{}, url: "http://0.0.0.0/abc/index.jsp"}, request_url: "http://0.0.0.0/abc/index.jsp", status_code: 302}}, :headers, [])
        (httprdf) lib/httprdf/http_request.ex:35: HttpRequest.post/5
        (elixir) lib/enum.ex:765: Enum."-each/2-lists^foreach/1-0-"/2
        (elixir) lib/enum.ex:765: Enum.each/2
        (httprdf) lib/httprdf/worker.ex:23: HTTPWorker.handle_info/2
        (stdlib) gen_server.erl:637: :gen_server.try_dispatch/4
        (stdlib) gen_server.erl:711: :gen_server.handle_msg/6
        (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
    13:00:44.327 [error] gen_server <0.361.0> terminated with reason: bad argument in call to erlang:apply({ok,#{'__struct__' => 'Elixir.HTTPoison.Response',body => <<>>,headers => [{<<"Server">>,<<"Apac...">>},...],...}}, headers, []) in 'Elixir.HttpRequest':post/5 line 35

Take a careful look at the output of IO.inspect(resp). Notice, it isn’t a struct, it’s a struct wrapped in a tuple: {:ok, %HTTPoison.Response}.

You need to unwrap that.

{:ok, resp} = HTTPoison.whatever
IO.inspect resp.headers

You can see this in the error message too, it’s telling you that you’re trying to call .headers on a tuple.

Whoops! I spent an hour not realizing this.
Thanks for the quick reply and making my first few steps into elixir a little bit easier :slight_smile:

1 Like