Combo.Router (combo v0.8.0)
View SourceDefines a router.
The router provides a set of macros for generating routes that dispatch to specific controllers and actions. Those macros are named after HTTP verbs. For example:
defmodule MyApp.Web.Router do
use Combo.Router
get "/pages/:page", MyApp.Web.PageController, :show
endCombo's router is extremely efficient, as it relies on pattern matching for matching routes.
Routing
get/3, post/3, put/3, and other macros named after HTTP verbs are used
to create routes.
The route:
get "/pages", PageController, :indexmatches a GET request to /pages and dispatches it to the index action
in PageController.
get "/pages/:page", PageController, :showmatches /pages/hello and dispatches to the show action in PageController
with %{"page" => "hello"} in params.
defmodule PageController do
def show(conn, params) do
# %{"page" => "hello"} == params
end
endPartial and multiple segments can be matched. For example:
get "/api/v:version/pages/:id", PageController, :showmatches /api/v1/pages/2 and puts %{"version" => "1", "id" => "2"} in
params. Only the trailing part of a segment can be captured.
Routes are matched from top to bottom. The second route here:
get "/pages/:page", PageController, :show
get "/pages/hello", PageController, :hellowill never match /pages/hello because /pages/:page matches that first.
Routes can use glob-like patterns to match trailing segments.
get "/pages/*page", PageController, :showmatches /pages/hello/world and puts the globbed segments in params["page"].
GET /pages/hello/world
%{"page" => ["hello", "world"]} = paramsGlobs cannot have prefixes nor suffixes, but can be mixed with variables:
get "/pages/he:page/*rest", PageController, :showmatches
GET /pages/hello
%{"page" => "llo", "rest" => []} = params
GET /pages/hey/there/world
%{"page" => "y", "rest" => ["there" "world"]} = paramsWhy the macros?
Combo does its best to keep the usage of macros low. You may have noticed,
however, that the Combo.Router relies heavily on macros. Why is that?
We use macros for one purposes:
- To be faster. They define the routing engine, used on every request, to choose which controller to dispatch the request to. Thanks to macros, Combo compiles all of your routes to a single case-statement with pattern matching rules, which is heavily optimized by the Erlang VM.
Route helpers
Combo generates a module Helpers for your routes, which contains named
helpers to help you generate and keep your routes up to date.
Helpers are automatically generated based on the controller name. For example, the route:
get "/pages/:page", PageController, :showwill generate the following named helper:
MyApp.Web.Router.Helpers.page_path(conn, :show, "hello")
"/pages/hello"
MyApp.Web.Router.Helpers.page_path(conn, :show, "hello", some: "query")
"/pages/hello?some=query"
MyApp.Web.Router.Helpers.page_url(conn, :show, "hello")
"http://example.com/pages/hello"
MyApp.Web.Router.Helpers.page_url(conn, :show, "hello", some: "query")
"http://example.com/pages/hello?some=query"If the route contains glob-like patterns, parameters for those have to be given as list:
MyApp.Web.Router.Helpers.page_path(conn, :show, ["hello", "world"])
"/pages/hello/world"The named helper can also be customized with the :as option. Given
the route:
get "/pages/:page", PageController, :show, as: :special_pagethe named helper will be:
MyApp.Web.Router.Helpers.special_page_path(conn, :show, "hello")
"/pages/hello"See the Combo.Router.Helpers for more information.
Scopes and Resources
It is very common to namespace routes under a scope. For example:
scope "/", MyApp.Web do
get "/pages/:id", PageController, :show
endThe route above will dispatch to MyApp.Web.PageController. This syntax is
convenient to use, since you don't have to repeat MyApp.Web. prefix on all
routes.
Like all paths, you can define dynamic segments that will be applied as parameters in the controller. For example:
scope "/api/:version", MyApp.Web do
get "/pages/:id", PageController, :show
endThe route above will match on the path "/api/v1/pages/1" and in the
controller the params argument be a map like
%{"version" => "v1", "id" => "1"}.
Combo also provides a resources/4 macro that allows to generate "RESTful"
routes to a given resource:
defmodule MyApp.Web.Router do
use Combo.Router
resources "/pages", PageController, only: [:show]
resources "/users", UserController, except: [:delete]
endCheck scope/2 and resources/4 for more information.
Listing routes
Combo ships with a mix combo.routes task that formats all routes in a given
router. We can use it to verify all routes included in the router.
Pipelines and plugs
Once a request arrives at the Combo router, it performs a series of transformations through pipelines until the request is dispatched to a desired route.
Such transformations are defined via plugs, as defined in the Plug specification.
Once a pipeline is defined, it can be piped through per scope.
For example:
defmodule MyApp.Web.Router do
use Combo.Router
import Combo.Controller
import Plug.Conn
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
end
scope "/" do
pipe_through :browser
# browser related routes
# ...
end
endIn the example above, we also imports Combo.Controller and Plug.Conn to
help defining plugins. accepts/2 comes from Combo.Controller, while
fetch_session/2 comes from Plug.Conn.
Note that router pipelines are only invoked after a route is found. No plug is invoked in case no matches were found.
Summary
Reflection
Returns the compile-time route info and runtime path params for a request.
Returns the full alias with the current scope's aliased prefix.
Returns the full path with the current scope's path prefix.
Functions
Defines a route to handle a connect request to the given path.
Defines a route to handle a delete request to the given path.
Forwards a request at the given path to a plug.
Defines a route to handle a get request to the given path.
Defines a route to handle a head request to the given path.
Defines a route based on an arbitrary HTTP method.
Defines a route to handle a options request to the given path.
Defines a route to handle a patch request to the given path.
Defines a list of plugs (and pipelines) to send the connection through.
Defines a plug pipeline.
Defines a plug inside a pipeline.
Defines a route to handle a post request to the given path.
Defines a route to handle a put request to the given path.
Defines "RESTful" routes for a resource.
Returns all routes information from the given router.
Defines a scope in which routes can be nested.
Define a scope with the given path.
Defines a scope with the given path and alias.
Defines a route to handle a trace request to the given path.
Reflection
Returns the compile-time route info and runtime path params for a request.
The path can be either a string or the path_info segments.
A map of metadata is returned with the following keys:
:log- the configured log level, such as:debug.:path_params- the map of runtime path params.:pipe_through- the list of pipelines for the route's scope, such as[:browser].:plug- the plug to dispatch the route to, such asMyApp.Web.PostController.:plug_opts- the options to pass when calling the plug, such as:index.:route- the string route pattern, such as"/posts/:id".
Examples
iex> Combo.Router.route_info(MyApp.Web.Router, "GET", "/posts/123", "myhost")
%{
log: :debug,
path_params: %{"id" => "123"},
pipe_through: [:browser],
plug: MyApp.Web.PostController,
plug_opts: :show,
route: "/posts/:id",
}
iex> Combo.Router.route_info(MyRouter, "GET", "/not-exists", "myhost")
:error
Returns the full alias with the current scope's aliased prefix.
Useful for applying the same short-hand alias handling to other values besides the second argument in route definitions.
Examples
scope "/", MyPrefix do
get "/", ProxyPlug, controller: scoped_alias(__MODULE__, MyController)
end
Returns the full path with the current scope's path prefix.
Functions
Defines a route to handle a connect request to the given path.
connect "/events/:id", EventController, :actionSee match/5 for options.
Defines a route to handle a delete request to the given path.
delete "/events/:id", EventController, :actionSee match/5 for options.
Forwards a request at the given path to a plug.
This is commonly used to forward all subroutes to another Plug. For example:
forward "/admin", SomeLib.AdminDashboardThe above will allow SomeLib.AdminDashboard to handle /admin,
/admin/foo, /admin/bar/baz, and so on. Furthermore,
SomeLib.AdminDashboard does not to be aware of the prefix it
is mounted in. From its point of view, the routes above are simply
handled as /, /foo, and /bar/baz.
A common use case for forward is for sharing a router between
applications or breaking a big router into smaller ones.
However, in other for route generation to route accordingly, you
can only forward to a given Combo.Router once.
The router pipelines will be invoked prior to forwarding the connection.
Examples
scope "/", MyApp do
pipe_through [:browser, :admin]
forward "/admin", SomeLib.AdminDashboard
forward "/api", ApiRouter
end
Defines a route to handle a get request to the given path.
get "/events/:id", EventController, :actionSee match/5 for options.
Defines a route to handle a head request to the given path.
head "/events/:id", EventController, :actionSee match/5 for options.
Compatibility with Plug.Head
By default, Combo apps include Plug.Head in their endpoint, which converts
HEAD requests into regular GET requests. Therefore, if you intend to use
head/4 in your router, you need to move Plug.Head to inside your router
in a way it does not conflict with the paths given to head/4.
Defines a route based on an arbitrary HTTP method.
Useful for defining routes not included in the built-in macros.
The catch-all verb, :*, may also be used to match all HTTP methods.
Options
:as- the named helper. Ifnil, does not generate a helper.:alias- if the scope alias should be applied to the route. Defaults totrue.:log- the level to log the route dispatching under, may be set to false. Defaults to:debug. Route dispatching contains information about how the route is handled (which controller action is called, what parameters are available and which pipelines are used) and is separate from the plug level logging. To alter the plug log level, please see https://hexdocs.pm/combo/Combo.Logger.html#module-dynamic-log-level.:private- a map of private data to merge into the connection when a a route matches.:assigns- a map of data to merge into the connection when a route matches.:metadata- a map of metadata used by the telemetry events and returned byroute_info/4. The:mfafield is used by telemetry to print logs and by the router to emit compile time checks. Custom fields may be added.
Examples
match :move, "/events/:id", EventController, :move
match :*, "/any", CatchAllController, :any
Defines a route to handle a options request to the given path.
options "/events/:id", EventController, :actionSee match/5 for options.
Defines a route to handle a patch request to the given path.
patch "/events/:id", EventController, :actionSee match/5 for options.
Defines a list of plugs (and pipelines) to send the connection through.
Plugs are specified using the atom name of any imported 2-arity function
which takes a Plug.Conn struct and options and returns a Plug.Conn struct.
For example, :require_authenticated_user.
Pipelines are defined in the router, see pipeline/2 for more information.
pipe_through [:require_authenticated_user, :my_browser_pipeline]Multiple invocations
pipe_through/1 can be invoked multiple times within the same scope. Each
invocation appends new plugs and pipelines to run, which are applied to all
routes after the pipe_through/1 invocation. For example:
scope "/" do
pipe_through [:browser]
get "/", HomeController, :index
pipe_through [:require_authenticated_user]
get "/settings", UserController, :edit
endIn the example above, / pipes through browser only, while /settings pipes
through both browser and require_authenticated_user. Therefore, to avoid
confusion, we recommend a single pipe_through at the top of each scope:
scope "/" do
pipe_through [:browser]
get "/", HomeController, :index
end
scope "/" do
pipe_through [:browser, :require_authenticated_user]
get "/settings", UserController, :edit
end
Defines a plug pipeline.
Pipelines are defined at the router root and can be used from any scope.
Examples
pipeline :api do
plug :token_authentication
plug :dispatch
endA scope may then use this pipeline as:
scope "/" do
pipe_through :api
endEvery time pipe_through/1 is called, the new pipelines are appended to the
ones previously given.
Defines a plug inside a pipeline.
See pipeline/2 for more information.
Defines a route to handle a post request to the given path.
post "/events/:id", EventController, :actionSee match/5 for options.
Defines a route to handle a put request to the given path.
put "/events/:id", EventController, :actionSee match/5 for options.
See resources/4.
See resources/4.
Defines "RESTful" routes for a resource.
The given definition:
resources "/users", UserControllerwill include routes to the following actions:
GET /users=>:indexGET /users/new=>:newPOST /users=>:createGET /users/:id=>:showGET /users/:id/edit=>:editPATCH /users/:id=>:updatePUT /users/:id=>:updateDELETE /users/:id=>:delete
Options
This macro accepts a set of options:
:only- a list of actions to generate routes for, for example:[:show, :edit]:except- a list of actions to exclude generated routes from, for example:[:delete]:param- the name of the parameter for this resource, defaults to"id":name- the prefix for this resource. This is used for the named helper and as the prefix for the parameter in nested resources. The default value is automatically derived from the controller name, i.e.UserControllerwill have name"user".:as- configures the named helper. Ifnil, does not generate a helper.:singleton- defines routes for a singleton resource. Read below for more information.
Singleton resources
When a resource needs to be looked up without referencing an ID, because
it contains only a single entry in the given context, the :singleton
option can be used to generate a set of routes that are specific to
such single resource:
GET /user/new=>:newPOST /user=>:createGET /user=>:showGET /user/edit=>:editPATCH /user=>:updatePUT /user=>:updateDELETE /user=>:delete
Usage example:
resources "/account", AccountController, only: [:show], singleton: trueNested Resources
This macro also supports passing a nested block of route definitions. This is helpful for nesting children resources within their parents to generate nested routes.
The given definition:
resources "/users", UserController do
resources "/posts", PostController
endwill include the following routes:
user_post_path GET /users/:user_id/posts PostController :index
user_post_path GET /users/:user_id/posts/new PostController :new
user_post_path POST /users/:user_id/posts PostController :create
user_post_path GET /users/:user_id/posts/:id PostController :show
user_post_path GET /users/:user_id/posts/:id/edit PostController :edit
user_post_path PATCH /users/:user_id/posts/:id PostController :update
PUT /users/:user_id/posts/:id PostController :update
user_post_path DELETE /users/:user_id/posts/:id PostController :delete
Returns all routes information from the given router.
Defines a scope in which routes can be nested.
Examples
scope path: "/api/v1", alias: API.V1 do
get "/pages/:id", PageController, :show
endThe generated route above will match on the path "/api/v1/pages/:id"
and will dispatch to :show action in API.V1.PageController. A named
helper api_v1_page_path will also be generated.
Options
The supported options are:
:path- a string containing the path scope.:as- a string or atom containing the named helper scope. When set to false, it resets the nested helper scopes. Has no effect when using verified routes exclusively:alias- an alias (atom) containing the controller scope. When set to false, it resets all nested aliases.:host- a string or list of strings containing the host scope, or prefix host scope, ie"foo.bar.com","foo.":private- a map of private data to merge into the connection when a route matches:assigns- a map of data to merge into the connection when a route matches:log- the level to log the route dispatching under, may be set to false. Defaults to:debug. Route dispatching contains information about how the route is handled (which controller action is called, what parameters are available and which pipelines are used) and is separate from the plug level logging. To alter the plug log level, please see https://hexdocs.pm/combo/Combo.Logger.html#module-dynamic-log-level.
Define a scope with the given path.
This function is a shortcut for:
scope path: path do
...
endExamples
scope "/v1", host: "api." do
get "/pages/:id", PageController, :show
end
Defines a scope with the given path and alias.
This function is a shortcut for:
scope path: path, alias: alias do
...
endExamples
scope "/v1", API.V1, host: "api." do
get "/pages/:id", PageController, :show
end
Defines a route to handle a trace request to the given path.
trace "/events/:id", EventController, :actionSee match/5 for options.