routing.asciidoc 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. [[routing]]
  2. == Routing
  3. Cowboy does nothing by default.
  4. To make Cowboy useful, you need to map URIs to Erlang modules that will
  5. handle the requests. This is called routing.
  6. When Cowboy receives a request, it tries to match the requested host and
  7. path to the configured routes. When there's a match, the route's
  8. associated handler is executed.
  9. Routes need to be compiled before they can be used by Cowboy.
  10. The result of the compilation is the dispatch rules.
  11. === Syntax
  12. The general structure for the routes is defined as follow.
  13. [source,erlang]
  14. Routes = [Host1, Host2, ... HostN].
  15. Each host contains matching rules for the host along with optional
  16. constraints, and a list of routes for the path component.
  17. [source,erlang]
  18. Host1 = {HostMatch, PathsList}.
  19. Host2 = {HostMatch, Constraints, PathsList}.
  20. The list of routes for the path component is defined similar to the
  21. list of hosts.
  22. [source,erlang]
  23. PathsList = [Path1, Path2, ... PathN].
  24. Finally, each path contains matching rules for the path along with
  25. optional constraints, and gives us the handler module to be used
  26. along with its initial state.
  27. [source,erlang]
  28. Path1 = {PathMatch, Handler, InitialState}.
  29. Path2 = {PathMatch, Constraints, Handler, InitialState}.
  30. Continue reading to learn more about the match syntax and the optional
  31. constraints.
  32. === Match syntax
  33. The match syntax is used to associate host names and paths with their
  34. respective handlers.
  35. The match syntax is the same for host and path with a few subtleties.
  36. Indeed, the segments separator is different, and the host is matched
  37. starting from the last segment going to the first. All examples will
  38. feature both host and path match rules and explain the differences
  39. when encountered.
  40. Excluding special values that we will explain at the end of this section,
  41. the simplest match value is a host or a path. It can be given as either
  42. a `string()` or a `binary()`.
  43. [source,erlang]
  44. ----
  45. PathMatch1 = "/".
  46. PathMatch2 = "/path/to/resource".
  47. HostMatch1 = "cowboy.example.org".
  48. ----
  49. As you can see, all paths defined this way must start with a slash
  50. character. Note that these two paths are identical as far as routing
  51. is concerned.
  52. [source,erlang]
  53. PathMatch2 = "/path/to/resource".
  54. PathMatch3 = "/path/to/resource/".
  55. Hosts with and without a trailing dot are equivalent for routing.
  56. Similarly, hosts with and without a leading dot are also equivalent.
  57. [source,erlang]
  58. HostMatch1 = "cowboy.example.org".
  59. HostMatch2 = "cowboy.example.org.".
  60. HostMatch3 = ".cowboy.example.org".
  61. It is possible to extract segments of the host and path and to store
  62. the values in the `Req` object for later use. We call these kind of
  63. values bindings.
  64. The syntax for bindings is very simple. A segment that begins with
  65. the `:` character means that what follows until the end of the segment
  66. is the name of the binding in which the segment value will be stored.
  67. [source,erlang]
  68. PathMatch = "/hats/:name/prices".
  69. HostMatch = ":subdomain.example.org".
  70. If these two end up matching when routing, you will end up with two
  71. bindings defined, `subdomain` and `name`, each containing the
  72. segment value where they were defined. For example, the URL
  73. `http://test.example.org/hats/wild_cowboy_legendary/prices` will
  74. result in having the value `test` bound to the name `subdomain`
  75. and the value `wild_cowboy_legendary` bound to the name `name`.
  76. They can later be retrieved using `cowboy_req:binding/{2,3}`. The
  77. binding name must be given as an atom.
  78. There is a special binding name you can use to mimic the underscore
  79. variable in Erlang. Any match against the `_` binding will succeed
  80. but the data will be discarded. This is especially useful for
  81. matching against many domain names in one go.
  82. [source,erlang]
  83. HostMatch = "ninenines.:_".
  84. Similarly, it is possible to have optional segments. Anything
  85. between brackets is optional.
  86. [source,erlang]
  87. PathMatch = "/hats/[page/:number]".
  88. HostMatch = "[www.]ninenines.eu".
  89. You can also have imbricated optional segments.
  90. [source,erlang]
  91. PathMatch = "/hats/[page/[:number]]".
  92. You can retrieve the rest of the host or path using `[...]`.
  93. In the case of hosts it will match anything before, in the case
  94. of paths anything after the previously matched segments. It is
  95. a special case of optional segments, in that it can have
  96. zero, one or many segments. You can then find the segments using
  97. `cowboy_req:host_info/1` and `cowboy_req:path_info/1` respectively.
  98. They will be represented as a list of segments.
  99. [source,erlang]
  100. PathMatch = "/hats/[...]".
  101. HostMatch = "[...]ninenines.eu".
  102. If a binding appears twice in the routing rules, then the match
  103. will succeed only if they share the same value. This copies the
  104. Erlang pattern matching behavior.
  105. [source,erlang]
  106. PathMatch = "/hats/:name/:name".
  107. This is also true when an optional segment is present. In this
  108. case the two values must be identical only if the segment is
  109. available.
  110. [source,erlang]
  111. PathMatch = "/hats/:name/[:name]".
  112. If a binding is defined in both the host and path, then they must
  113. also share the same value.
  114. [source,erlang]
  115. PathMatch = "/:user/[...]".
  116. HostMatch = ":user.github.com".
  117. Finally, there are two special match values that can be used. The
  118. first is the atom `'_'` which will match any host or path.
  119. [source,erlang]
  120. PathMatch = '_'.
  121. HostMatch = '_'.
  122. The second is the special host match `"*"` which will match the
  123. wildcard path, generally used alongside the `OPTIONS` method.
  124. [source,erlang]
  125. HostMatch = "*".
  126. === Constraints
  127. After the matching has completed, the resulting bindings can be tested
  128. against a set of constraints. Constraints are only tested when the
  129. binding is defined. They run in the order you defined them. The match
  130. will succeed only if they all succeed. If the match fails, then Cowboy
  131. tries the next route in the list.
  132. The format used for constraints is the same as match functions in
  133. `cowboy_req`: they are provided as a list of fields which may have
  134. one or more constraints. While the router accepts the same format,
  135. it will skip fields with no constraints and will also ignore default
  136. values, if any.
  137. Read more about xref:constraints[constraints].
  138. === Compilation
  139. The routes must be compiled before Cowboy can use them. The compilation
  140. step normalizes the routes to simplify the code and speed up the
  141. execution, but the routes are still looked up one by one in the end.
  142. Faster compilation strategies could be to compile the routes directly
  143. to Erlang code, but would require heavier dependencies.
  144. To compile routes, just call the appropriate function:
  145. [source,erlang]
  146. ----
  147. Dispatch = cowboy_router:compile([
  148. %% {HostMatch, list({PathMatch, Handler, InitialState})}
  149. {'_', [{'_', my_handler, #{}}]}
  150. ]),
  151. %% Name, NbAcceptors, TransOpts, ProtoOpts
  152. cowboy:start_clear(my_http_listener, 100,
  153. [{port, 8080}],
  154. #{env => #{dispatch => Dispatch}}
  155. ).
  156. ----
  157. === Live update
  158. You can use the `cowboy:set_env/3` function for updating the dispatch
  159. list used by routing. This will apply to all new connections accepted
  160. by the listener:
  161. [source,erlang]
  162. cowboy:set_env(my_http_listener, dispatch, cowboy_router:compile(Dispatch)).
  163. Note that you need to compile the routes again before updating.