Skip to content

Instantly share code, notes, and snippets.

@starbelly
Created February 22, 2019 08:41
Show Gist options
  • Save starbelly/2b8bb044f880183e9841ade0875cb95c to your computer and use it in GitHub Desktop.
Save starbelly/2b8bb044f880183e9841ade0875cb95c to your computer and use it in GitHub Desktop.
plug.router: storing the matched route before dispatch
defmodule MatchMaker do
  use Plug.Router

  plug :match
  plug :post_match
  plug :dispatch

  def start_link do
    {:ok, _} = Plug.Adapters.Cowboy.http(__MODULE__, [], port: 4000)
  end

  def init(options) do
    options
  end

  get "/hello/:name" do
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(200, "{\"#{name}\": \"#{conn.assigns.matched_path}\"}")
  end

  match _ do
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(404, "{\"error\": \"eh?\"}")
  end

  # Note that match_path/1 comes from Plug.Router
  defp post_match(conn, _opts) do
    assign(conn, :matched_path, match_path(conn))
  end
end
Erlang/OTP 22 [DEVELOPMENT] [erts-10.2.3] [source-1414a4c] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]

Interactive Elixir (1.8.0) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> MatchMaker.start_link
{:ok, #PID<0.255.0>}
iex(2)> :httpc.request(:get, {'http://localhost:4000/hello/tristan', []}, [], [])
{:ok,
 {{'HTTP/1.1', 200, 'OK'},
  [
    {'cache-control', 'max-age=0, private, must-revalidate'},
    {'date', 'Fri, 22 Feb 2019 08:41:04 GMT'},
    {'server', 'Cowboy'},
    {'content-length', '27'},
    {'content-type', 'application/json; charset=utf-8'}
  ], '{"tristan": "/hello/:name"}'}}
iex(3)>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment