-
-
Save mraaroncruz/bd441a2995c951ce8be062e0d0130ff5 to your computer and use it in GitHub Desktop.
proxying responses
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 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