Skip to content

Instantly share code, notes, and snippets.

@bsuh
Last active July 16, 2020 20:00
Show Gist options
  • Save bsuh/295759580d36fe42a533abb733cb912c to your computer and use it in GitHub Desktop.
Save bsuh/295759580d36fe42a533abb733cb912c to your computer and use it in GitHub Desktop.
proxying responses
defmodule PhoenixTest.PageController do
use PhoenixTest.Web, :controller
def index(conn, _params) do
render conn, "index.html"
end
def proxy(conn, params) do
query_string = conn.query_string
path = Enum.join(params["path"], "/")
path = path <> case query_string do
"" -> ""
_ -> "?" <> query_string
end
headers = for {k, v} <- conn.req_headers do
{String.to_charlist(k), String.to_charlist(v)}
end
{:ok, {{status_code, _}, response_headers, body}} = :lhttpc.request(
'http://localhost:8090/#{path}', :get, headers, "", :infinity,
[{:partial_download, [{:window_size, 10}, {:part_size, 10000}]}])
response_headers = for {k, v} <- response_headers,
k != 'Transfer-Encoding' do {k, v} end
resp_body_function = fn socket, transport ->
stream_body(body, socket, transport)
end
{adapter, payload} = conn.adapter
{:ok, payload} = :cowboy_req.reply(status_code, response_headers, :cowboy_req.set_resp_body_fun(resp_body_function, payload))
%{conn | adapter: { adapter, payload }, resp_body: nil, state: :sent}
end
defp stream_body(body, socket, transport) do
case :lhttpc.get_body_part(body) do
{:ok, chunk} when is_binary(chunk) ->
transport.send(socket, chunk)
stream_body(body, socket, transport)
{:ok, {:http_eob, _}} -> nil
{:error, err} -> raise err
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment