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)>