Created
July 18, 2018 11:58
-
-
Save xolan/776e55356a9c45b93debe03ede82da2f to your computer and use it in GitHub Desktop.
Handle X-Forwarded-Prefix with Plug.Traefik
This file contains hidden or 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 Plug.Traefik do | |
use Plug.Builder | |
@assets_dir System.cwd <> "/priv/web/assets/" | |
plug Plug.Static, at: "/assets", from: @assets_dir | |
plug :x_forwarded_prefix | |
def x_forwarded_prefix(conn, _) do | |
register_before_send(conn, fn(conn) -> | |
case get_req_header(conn, "x-forwarded-prefix") do | |
[prefix] -> resp(conn, conn.status, replace(conn.resp_body, prefix)) | |
[] -> conn | |
end | |
end) | |
end | |
defp replace(source, prefix) when is_bitstring(source) do | |
case String.starts_with?(source, "/") do | |
true -> | |
String.replace(source, "/", prefix <> "/", global: false) | |
false -> | |
source | |
|> String.replace("src=\"/", "src=\"" <> prefix <> "/") | |
|> String.replace("href=\"/", "href=\"" <> prefix <> "/") | |
end | |
end | |
defp replace(source, prefix) when is_list(source) do | |
source | |
|> Enum.map(fn item -> replace(item, prefix) end) | |
end | |
defp replace(source, _prefix) do | |
source | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment