| 1 |
[[routing]] |
| 2 |
== Routing |
| 3 |
|
| 4 |
Cowboy does nothing by default. |
| 5 |
|
| 6 |
To make Cowboy useful, you need to map URIs to Erlang modules that will |
| 7 |
handle the requests. This is called routing. |
| 8 |
|
| 9 |
Cowboy routes requests using the following algorithm: |
| 10 |
|
| 11 |
* If no configured host matches the request URI, a 400 response |
| 12 |
is returned. |
| 13 |
|
| 14 |
* Otherwise, the first configured host that matches the request |
| 15 |
URI will be used. Only the paths configured for this host will |
| 16 |
be considered. |
| 17 |
|
| 18 |
* If none of the configured paths found in the previous step |
| 19 |
match the request URI, a 404 response is returned. |
| 20 |
|
| 21 |
* Otherwise, the handler and its initial state are added to the |
| 22 |
environment and the request continues to be processed. |
| 23 |
|
| 24 |
NOTE: It is possible to run into a situation where two hosts match a |
| 25 |
request URI, but only the paths on the second host match the |
| 26 |
request URI. In this case the expected result is a 404 response |
| 27 |
because the only paths used during routing are the paths from |
| 28 |
the first configured host that matches the request URI. |
| 29 |
|
| 30 |
Routes need to be compiled before they can be used by Cowboy. |
| 31 |
The result of the compilation is the dispatch rules. |
| 32 |
|
| 33 |
=== Syntax |
| 34 |
|
| 35 |
The general structure for the routes is defined as follow. |
| 36 |
|
| 37 |
[source,erlang] |
| 38 |
Routes = [Host1, Host2, ... HostN]. |
| 39 |
|
| 40 |
Each host contains matching rules for the host along with optional |
| 41 |
constraints, and a list of routes for the path component. |
| 42 |
|
| 43 |
[source,erlang] |
| 44 |
Host1 = {HostMatch, PathsList}. |
| 45 |
Host2 = {HostMatch, Constraints, PathsList}. |
| 46 |
|
| 47 |
The list of routes for the path component is defined similar to the |
| 48 |
list of hosts. |
| 49 |
|
| 50 |
[source,erlang] |
| 51 |
PathsList = [Path1, Path2, ... PathN]. |
| 52 |
|
| 53 |
Finally, each path contains matching rules for the path along with |
| 54 |
optional constraints, and gives us the handler module to be used |
| 55 |
along with its initial state. |
| 56 |
|
| 57 |
[source,erlang] |
| 58 |
Path1 = {PathMatch, Handler, InitialState}. |
| 59 |
Path2 = {PathMatch, Constraints, Handler, InitialState}. |
| 60 |
|
| 61 |
Continue reading to learn more about the match syntax and the optional |
| 62 |
constraints. |
| 63 |
|
| 64 |
=== Match syntax |
| 65 |
|
| 66 |
The match syntax is used to associate host names and paths with their |
| 67 |
respective handlers. |
| 68 |
|
| 69 |
The match syntax is the same for host and path with a few subtleties. |
| 70 |
Indeed, the segments separator is different, and the host is matched |
| 71 |
starting from the last segment going to the first. All examples will |
| 72 |
feature both host and path match rules and explain the differences |
| 73 |
when encountered. |
| 74 |
|
| 75 |
Excluding special values that we will explain at the end of this section, |
| 76 |
the simplest match value is a host or a path. It can be given as either |
| 77 |
a `string()` or a `binary()`. |
| 78 |
|
| 79 |
[source,erlang] |
| 80 |
---- |
| 81 |
PathMatch1 = "/". |
| 82 |
PathMatch2 = "/path/to/resource". |
| 83 |
|
| 84 |
HostMatch1 = "cowboy.example.org". |
| 85 |
---- |
| 86 |
|
| 87 |
As you can see, all paths defined this way must start with a slash |
| 88 |
character. Note that these two paths are identical as far as routing |
| 89 |
is concerned. |
| 90 |
|
| 91 |
[source,erlang] |
| 92 |
PathMatch2 = "/path/to/resource". |
| 93 |
PathMatch3 = "/path/to/resource/". |
| 94 |
|
| 95 |
Hosts with and without a trailing dot are equivalent for routing. |
| 96 |
Similarly, hosts with and without a leading dot are also equivalent. |
| 97 |
|
| 98 |
[source,erlang] |
| 99 |
HostMatch1 = "cowboy.example.org". |
| 100 |
HostMatch2 = "cowboy.example.org.". |
| 101 |
HostMatch3 = ".cowboy.example.org". |
| 102 |
|
| 103 |
It is possible to extract segments of the host and path and to store |
| 104 |
the values in the `Req` object for later use. We call these kind of |
| 105 |
values bindings. |
| 106 |
|
| 107 |
The syntax for bindings is very simple. A segment that begins with |
| 108 |
the `:` character means that what follows until the end of the segment |
| 109 |
is the name of the binding in which the segment value will be stored. |
| 110 |
|
| 111 |
[source,erlang] |
| 112 |
PathMatch = "/hats/:name/prices". |
| 113 |
HostMatch = ":subdomain.example.org". |
| 114 |
|
| 115 |
If these two end up matching when routing, you will end up with two |
| 116 |
bindings defined, `subdomain` and `name`, each containing the |
| 117 |
segment value where they were defined. For example, the URL |
| 118 |
`http://test.example.org/hats/wild_cowboy_legendary/prices` will |
| 119 |
result in having the value `test` bound to the name `subdomain` |
| 120 |
and the value `wild_cowboy_legendary` bound to the name `name`. |
| 121 |
They can later be retrieved using `cowboy_req:binding/{2,3}`. The |
| 122 |
binding name must be given as an atom. |
| 123 |
|
| 124 |
There is a special binding name you can use to mimic the underscore |
| 125 |
variable in Erlang. Any match against the `_` binding will succeed |
| 126 |
but the data will be discarded. This is especially useful for |
| 127 |
matching against many domain names in one go. |
| 128 |
|
| 129 |
[source,erlang] |
| 130 |
HostMatch = "ninenines.:_". |
| 131 |
|
| 132 |
Similarly, it is possible to have optional segments. Anything |
| 133 |
between brackets is optional. |
| 134 |
|
| 135 |
[source,erlang] |
| 136 |
PathMatch = "/hats/[page/:number]". |
| 137 |
HostMatch = "[www.]ninenines.eu". |
| 138 |
|
| 139 |
You can also have imbricated optional segments. |
| 140 |
|
| 141 |
[source,erlang] |
| 142 |
PathMatch = "/hats/[page/[:number]]". |
| 143 |
|
| 144 |
While Cowboy does not reject multiple brackets in a route, |
| 145 |
the behavior may be undefined if the route is under-specified. |
| 146 |
For example, this route requires constraints to determine what |
| 147 |
is a chapter and what is a page, since they are both optional: |
| 148 |
|
| 149 |
[source,erlang] |
| 150 |
PathMatch = "/book/[:chapter]/[:page]". |
| 151 |
|
| 152 |
You can retrieve the rest of the host or path using `[...]`. |
| 153 |
In the case of hosts it will match anything before, in the case |
| 154 |
of paths anything after the previously matched segments. It is |
| 155 |
a special case of optional segments, in that it can have |
| 156 |
zero, one or many segments. You can then find the segments using |
| 157 |
`cowboy_req:host_info/1` and `cowboy_req:path_info/1` respectively. |
| 158 |
They will be represented as a list of segments. |
| 159 |
|
| 160 |
[source,erlang] |
| 161 |
PathMatch = "/hats/[...]". |
| 162 |
HostMatch = "[...]ninenines.eu". |
| 163 |
|
| 164 |
If a binding appears twice in the routing rules, then the match |
| 165 |
will succeed only if they share the same value. This copies the |
| 166 |
Erlang pattern matching behavior. |
| 167 |
|
| 168 |
[source,erlang] |
| 169 |
PathMatch = "/hats/:name/:name". |
| 170 |
|
| 171 |
This is also true when an optional segment is present. In this |
| 172 |
case the two values must be identical only if the segment is |
| 173 |
available. |
| 174 |
|
| 175 |
[source,erlang] |
| 176 |
PathMatch = "/hats/:name/[:name]". |
| 177 |
|
| 178 |
If a binding is defined in both the host and path, then they must |
| 179 |
also share the same value. |
| 180 |
|
| 181 |
[source,erlang] |
| 182 |
PathMatch = "/:user/[...]". |
| 183 |
HostMatch = ":user.github.com". |
| 184 |
|
| 185 |
Finally, there are two special match values that can be used. The |
| 186 |
first is the atom `'_'` which will match any host or path. |
| 187 |
|
| 188 |
[source,erlang] |
| 189 |
PathMatch = '_'. |
| 190 |
HostMatch = '_'. |
| 191 |
|
| 192 |
The second is the special host match `"*"` which will match the |
| 193 |
wildcard path, generally used alongside the `OPTIONS` method. |
| 194 |
|
| 195 |
[source,erlang] |
| 196 |
HostMatch = "*". |
| 197 |
|
| 198 |
=== Constraints |
| 199 |
|
| 200 |
After the matching has completed, the resulting bindings can be tested |
| 201 |
against a set of constraints. Constraints are only tested when the |
| 202 |
binding is defined. They run in the order you defined them. The match |
| 203 |
will succeed only if they all succeed. If the match fails, then Cowboy |
| 204 |
tries the next route in the list. |
| 205 |
|
| 206 |
The format used for constraints is the same as match functions in |
| 207 |
`cowboy_req`: they are provided as a list of fields which may have |
| 208 |
one or more constraints. While the router accepts the same format, |
| 209 |
it will skip fields with no constraints and will also ignore default |
| 210 |
values, if any. |
| 211 |
|
| 212 |
Read more about xref:constraints[constraints]. |
| 213 |
|
| 214 |
=== Compilation |
| 215 |
|
| 216 |
The routes must be compiled before Cowboy can use them. The compilation |
| 217 |
step normalizes the routes to simplify the code and speed up the |
| 218 |
execution, but the routes are still looked up one by one in the end. |
| 219 |
Faster compilation strategies could be to compile the routes directly |
| 220 |
to Erlang code, but would require heavier dependencies. |
| 221 |
|
| 222 |
To compile routes, just call the appropriate function: |
| 223 |
|
| 224 |
[source,erlang] |
| 225 |
---- |
| 226 |
Dispatch = cowboy_router:compile([ |
| 227 |
%% {HostMatch, list({PathMatch, Handler, InitialState})} |
| 228 |
{'_', [{'_', my_handler, #{}}]} |
| 229 |
]), |
| 230 |
%% Name, TransOpts, ProtoOpts |
| 231 |
cowboy:start_clear(my_http_listener, |
| 232 |
[{port, 8080}], |
| 233 |
#{env => #{dispatch => Dispatch}} |
| 234 |
). |
| 235 |
---- |
| 236 |
|
| 237 |
=== Using persistent_term |
| 238 |
|
| 239 |
The routes can be stored in `persistent_term` starting from |
| 240 |
Erlang/OTP 21.2. This may give a performance improvement when |
| 241 |
there are a large number of routes. |
| 242 |
|
| 243 |
To use this functionality you need to compile the routes, |
| 244 |
store them in `persistent_term` and then inform Cowboy: |
| 245 |
|
| 246 |
[source,erlang] |
| 247 |
---- |
| 248 |
Dispatch = cowboy_router:compile([ |
| 249 |
{'_', [{'_', my_handler, #{}}]} |
| 250 |
]), |
| 251 |
persistent_term:put(my_app_dispatch, Dispatch), |
| 252 |
cowboy:start_clear(my_http_listener, |
| 253 |
[{port, 8080}], |
| 254 |
#{env => #{dispatch => {persistent_term, my_app_dispatch}}} |
| 255 |
). |
| 256 |
---- |
| 257 |
|
| 258 |
=== Live update |
| 259 |
|
| 260 |
You can use the `cowboy:set_env/3` function for updating the dispatch |
| 261 |
list used by routing. This will apply to all new connections accepted |
| 262 |
by the listener: |
| 263 |
|
| 264 |
[source,erlang] |
| 265 |
Dispatch = cowboy_router:compile(Routes), |
| 266 |
cowboy:set_env(my_http_listener, dispatch, Dispatch). |
| 267 |
|
| 268 |
Note that you need to compile the routes again before updating. |
| 269 |
|
| 270 |
When using `persistent_term` there is no need to call this function, |
| 271 |
you can simply put the new routes in the storage. |