Last active
October 3, 2019 10:20
-
-
Save venkatd/20db80f32c535fca0610018066cb637d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Minty do | |
defmodule Response do | |
defstruct [:status, :headers, :data] | |
end | |
def request(method, url, opts \\ []) do | |
%{scheme: scheme, host: host, port: port, path: path} = URI.parse(url) | |
payload = Keyword.get(opts, :payload) | |
headers = Keyword.get(opts, :headers, []) | |
with {:ok, conn} <- Mint.HTTP.connect(String.to_atom(scheme), host, port), | |
{:ok, conn, _ref} <- | |
Mint.HTTP.request(conn, method, path, headers, encode!(payload)), | |
{:ok, conn, response} <- fetch_response(conn) do | |
{:ok, _conn} = Mint.HTTP.close(conn) | |
to_response(response) | |
end | |
end | |
defp fetch_response(conn) do | |
Mint.HTTP.stream( | |
conn, | |
receive do | |
msg -> msg | |
end | |
) | |
end | |
defp to_response([ | |
{:status, _, status}, | |
{:headers, _, headers}, | |
{:data, _, data}, | |
{:done, _} | |
]) do | |
case decode(data) do | |
{:ok, json} -> {:ok, %Response{status: status, headers: headers, data: json}} | |
{:error, error} -> {:error, error} | |
end | |
end | |
defp decode(response_data), do: Jason.decode(response_data) | |
defp encode!(nil), do: "" | |
defp encode!(request_payload), do: Jason.encode!(request_payload) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment