routing.asciidoc 7.0 KB

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