Understanding Plug.Router
Now that we know how a Plug
module works, let’s leverage one of the predefined plugs, Plug.Router
, to add functionality to our HTTP server. At the end of Chapter 2, we saw that to use our HTTP server for a proper REST API, we need a way to route incoming requests based on different paths and HTTP verbs. Cowboy has an internal way of routing the requests, but Plug.Router
allows us to do that in a very simple DSL. Another advantage of using Plug.Router
to route our requests, instead of using Cowboy directly, is that we can start using plugs earlier in our request-response cycle, even before they get to Cowboy. Here, we can only rely on Cowboy to send a response.
So, let’s start by defining a new plug, ExampleRouter
:
example_router.exs
Mix.install([ {:plug_cowboy, "~> 2.0"} ]) defmodule ExampleRouter do use Plug.Router plug :match plug :dispatch get "/greet"...