liveBook · Manning

Plug.Router

As explained in Elixir in Action, Third Edition

Plug.Router is a Plug module that provides a routing DSL for dispatching HTTP requests to handler code.

Plug.Router provides a routing DSL for dispatching HTTP requests to handler code. Calling use Plug.Router adds routing support, while plug :match and plug :dispatch arrange compile-time request matching and dispatch. section 11.3.3

A typical router assembles these pieces:

  • Declare routes with post or get macros, such as post "/add_entry" and get "/entries". section 11.3.3
  • Read query parameters through Plug.Conn, invoke application services, and send an HTTP response. section 11.3.3
  • Understand route declarations as macros that generate matching clauses and supporting boilerplate, rather than ordinary function definitions. section 11.3.3

Todo request routes

A router can handle POST /add_entry by fetching list, title, and date parameters, calling Todo.Server.add_entry, and returning OK. GET /entries retrieves entries and returns newline-formatted results. section 11.3.3

Listing 11.11 Setting up a route for add_entry (todo_web/lib/todo/web.ex)
defmodule Todo.Web do
  use Plug.Router          #1
 
  plug :match              #2
  plug :dispatch           #2
 
  ...
 
  post "/add_entry" do     #3
    ...
  end
 
  ...
end

Inspect the minimal router skeleton, then compare it with the generated do_match clauses and complete request handlers. section 11.3.3

How Elixir in Action, Third Edition covers it

How deep it goes
Explains route declarations, compile-time macros, generated matching clauses, and request handlers without detailing all Plug internals.
Examples
Uses todo routes for adding entries and retrieving date-filtered entries, exercised with curl requests.
What it assumes
Assumes familiarity with Elixir modules and macros while briefly explaining router-generated boilerplate.
What you can do after
Builds HTTP routes with Plug.Router and connects handlers to parameter parsing, application services, and responses.
How it connects
Connects Plug.Router with Plug.Conn, macros, HTTP methods, query parameters, and application service processes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.