Is it possible to use pattern match on Plug.router

Hey guys!

I’d like to know if it is possible to use pattern match on Plug.router to retrieve the params.

I’ve the following code:

post "/person" do
   %w{"name" => name} = conn.params
   send_resp(conn, 201, "")
end

I was trying to do something like this but it didn’t work:

post "/person", _,  %w{"name" => name} do
   send_resp(conn, 201, "")
end

Also, is this the correctly way to retrieve the params from request?

Thanks!!!

You can pattern match only on URLs and use guards but not on all params altogether. So this would work:

post "/person/:name" when byte_size(name) >= 3 do
  ...
end

Yours can’t be done in the route match. You will need case or another function for that.

2 Likes

Thanks Valim!

It was the full power of elixir pattern matching that led me to experiment creating an alternative to plug. Raxx would allow you to do the following.

def handle_request(%{method: "POST", path: ["person"], query: %{name: name}, _) do
  created("")
end

Maybe of interest but the project is definitely just an experiment.

3 Likes

Really cool project Peter!! Learn a lot digging into your code!

1 Like