Skip to content

Instantly share code, notes, and snippets.

@jc00ke
Created April 18, 2016 03:51
Show Gist options
  • Save jc00ke/2261e927ffca77f16965b9a2d3c815d1 to your computer and use it in GitHub Desktop.
Save jc00ke/2261e927ffca77f16965b9a2d3c815d1 to your computer and use it in GitHub Desktop.
def call(%Plug.Conn{req_headers: [{"authorization", token}]} = conn, _options) when is_binary(token) do
# I want this to match
conn
end
# this ends up matching
def call(conn, _), do: halt(conn)
conn = %{conn(:get, "/ping") | req_headers: [{"authorization", "asdf"}]}
call(conn) # matches the first, cool
conn = %{conn(:get, "/ping") | req_headers: [{"authorization", "asdf"}, {"foo", "bar"}]}
call(conn) # doesn't match first, but I want it to
# I guess I'm looking for something like -------------------v
def call(%Plug.Conn{req_headers: [{"authorization", token}, _]} = conn, _options)...
# or -------------------------------------------------------v
def call(%Plug.Conn{req_headers: [{"authorization", token}, *]} = conn, _options)...
# the following matches of course, but then I'd have to case against token being nil, which doesn't feel right.
def call(conn, _options) do
[token | _] = get_req_header(conn, "authorization")
# do stuff with token
conn
end
@ggpasqualino
Copy link

I think you can try %Plug.Conn{req_headers: [{"authorization", token} | other_headers]} = conn
EDIT:
This should be the equivalent of the match you are doing on https://gist.github.com/jc00ke/2261e927ffca77f16965b9a2d3c815d1#file-pattern_match_list-ex-L22

@mschae
Copy link

mschae commented Apr 18, 2016

I am pretty sure you can't. Headers are a prop list and you can't match for an item in a list by its value, only by its position.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment