Skip to content
Permalink
Browse files

Reuse HTTP connections

  • Loading branch information...
minhajuddin committed Jun 17, 2019
1 parent 4b0e7e2 commit bdb63d2b9cddac4af83d37dc9ff37a52ef6c123c
Showing with 27 additions and 4 deletions.
  1. +27 −4 lib/http/http.ex
@@ -14,17 +14,40 @@ defmodule HTTP do
when is_list(headers) and method in ~w[GET POST PUT PATCH DELETE OPTIONS HEAD] do
# TODO: spawn a new process per request so that the messages don't get intermingled

# get an existing connection if it is already available
conn = get_connection(uri)

Logger.info("#{method} #{uri}")
{:ok, conn} = Mint.HTTP.connect(scheme_atom(uri.scheme), uri.host, uri.port)

{:ok, conn, request_ref} = Mint.HTTP.request(conn, method, path(uri), headers, body)

{:ok, http_response = %HTTP.Response{}} = recv_response(conn, request_ref)
{:ok, http_response = %HTTP.Response{}, conn} = recv_response(conn, request_ref)

# put this connection in the process dictionary to be reused later
put_connection(uri, conn)

Mint.HTTP.close(conn)
{:ok, http_response}
end

# Put our connection in the process dictionary keyed on the hostname so that
# we don't reuse connections for different hosts.
defp put_connection(uri, conn) do
Process.put({:conn, uri.host}, conn)
end

# Get a connection if it was previously created, else create a new connection
defp get_connection(uri) do
conn = Process.get({:conn, uri.host})

if conn do
conn
else
Logger.info("creating HTTP connection to Github")
{:ok, conn} = Mint.HTTP.connect(scheme_atom(uri.scheme), uri.host, uri.port)
conn
end
end

defp recv_response(conn, request_ref, http_response \\ %HTTP.Response{}) do
receive do
message ->
@@ -34,7 +57,7 @@ defmodule HTTP do

case HTTP.Response.parse(mint_messages, request_ref, http_response) do
{:ok, http_response = %HTTP.Response{complete?: true}} ->
{:ok, http_response}
{:ok, http_response, conn}

{:ok, http_response} ->
recv_response(conn, request_ref, http_response)

0 comments on commit bdb63d2

Please sign in to comment.
You can’t perform that action at this time.