Skip to content

Commit

Permalink
Set Logger.metadata even if header parsing fails
Browse files Browse the repository at this point in the history
This fixes the tests added by e89412e.
They had been failing against the original implementation of #22.
  • Loading branch information
ajvondrak committed Jan 23, 2021
1 parent e89412e commit 944c9df
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions lib/remote_ip.ex
Original file line number Diff line number Diff line change
Expand Up @@ -121,18 +121,14 @@ defmodule RemoteIp do
end

def call(conn, %RemoteIp.Config{} = config) do
case last_forwarded_ip(conn.req_headers, config) do
nil -> conn
ip ->
Logger.metadata(remote_ip: convert_to_string(ip))
%{conn | remote_ip: ip}
with_metadata do
case last_forwarded_ip(conn.req_headers, config) do
nil -> conn
ip -> %{conn | remote_ip: ip}
end
end
end

defp convert_to_string(ip) do
ip |> :inet_parse.ntoa() |> to_string()
end

@doc """
Standalone function to extract the remote IP from a list of headers.
Expand Down Expand Up @@ -176,6 +172,14 @@ defmodule RemoteIp do
last_forwarded_ip(req_headers, init(opts))
end

defp with_metadata(do: conn) do
case :inet.ntoa(conn.remote_ip) do
{:error, _} -> nil
ip -> Logger.metadata(remote_ip: to_string(ip))
end
conn
end

defp last_forwarded_ip(req_headers, config) do
Logger.debug(fn -> start(config) end)
ip = req_headers |> ips_given(config) |> most_recent_client_given(config)
Expand Down

0 comments on commit 944c9df

Please sign in to comment.