req.asciidoc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. [[req]]
  2. == The Req object
  3. The Req object is a variable used for obtaining information
  4. about a request, read its body or send a response.
  5. It is not really an object in the object-oriented sense.
  6. It is a simple map that can be directly accessed or
  7. used when calling functions from the `cowboy_req` module.
  8. The Req object is the subject of a few different chapters.
  9. In this chapter we will learn about the Req object and
  10. look at how to retrieve information about the request.
  11. === Direct access
  12. The Req map contains a number of fields which are documented
  13. and can be accessed directly. They are the fields that have
  14. a direct mapping to HTTP: the request `method`; the HTTP
  15. `version` used; the effective URI components `scheme`,
  16. `host`, `port`, `path` and `qs`; the request `headers`;
  17. and the connection `peer` address and port.
  18. Note that the `version` field can be used to determine
  19. whether a connection is using HTTP/2.
  20. To access a field, you can simply match in the function
  21. head. The following example sends a simple "Hello world!"
  22. response when the `method` is GET, and a 405 error
  23. otherwise.
  24. [source,erlang]
  25. ----
  26. init(Req0=#{method := <<"GET">>}, State) ->
  27. Req = cowboy_req:reply(200, #{
  28. <<"content-type">> => <<"text/plain">>
  29. }, <<"Hello world!">>, Req0),
  30. {ok, Req, State};
  31. init(Req0, State) ->
  32. Req = cowboy_req:reply(405, #{
  33. <<"allow">> => <<"GET">>
  34. }, Req0),
  35. {ok, Req, State}.
  36. ----
  37. Any other field is internal and should not be accessed.
  38. They may change in future releases, including maintenance
  39. releases, without notice.
  40. Modifying the Req object, while allowed, is not recommended
  41. unless strictly necessary. If adding new fields, make sure
  42. to namespace the field names so that no conflict can occur
  43. with future Cowboy updates or third party projects.
  44. // @todo There are currently no tests for direct access.
  45. === Introduction to the cowboy_req interface
  46. // @todo Link to cowboy_req manual
  47. Functions in the `cowboy_req` module provide access to
  48. the request information but also various operations that
  49. are common when dealing with HTTP requests.
  50. All the functions that begin with a verb indicate an action.
  51. Other functions simply return the corresponding value
  52. (sometimes that value does need to be built, but the
  53. cost of the operation is equivalent to retrieving a value).
  54. Some of the `cowboy_req` functions return an updated Req
  55. object. They are the read, reply, set and delete functions.
  56. While ignoring the returned Req will not cause incorrect
  57. behavior for some of them, it is highly recommended to
  58. always keep and use the last returned Req object. The
  59. manual for `cowboy_req` details these functions and what
  60. modifications are done to the Req object.
  61. Some of the calls to `cowboy_req` have side effects. This
  62. is the case of the read and reply functions. Cowboy reads
  63. the request body or replies immediately when the function
  64. is called.
  65. All functions will crash if something goes wrong. There
  66. is usually no need to catch these errors, Cowboy will
  67. send the appropriate 4xx or 5xx response depending on
  68. where the crash occurred.
  69. === Request method
  70. The request method can be retrieved directly:
  71. [source, erlang]
  72. #{method := Method} = Req.
  73. Or using a function:
  74. [source,erlang]
  75. Method = cowboy_req:method(Req).
  76. The method is a case sensitive binary string. Standard
  77. methods include GET, HEAD, OPTIONS, PATCH, POST, PUT
  78. or DELETE.
  79. === HTTP version
  80. The HTTP version is informational. It does not indicate that
  81. the client implements the protocol well or fully.
  82. There is typically no need to change behavior based on the
  83. HTTP version: Cowboy already does it for you.
  84. It can be useful in some cases, though. For example, one may
  85. want to redirect HTTP/1.1 clients to use Websocket, while HTTP/2
  86. clients keep using HTTP/2.
  87. The HTTP version can be retrieved directly:
  88. [source,erlang]
  89. #{version := Version} = Req.
  90. Or using a function:
  91. [source,erlang]
  92. Version = cowboy_req:version(Req).
  93. Cowboy defines the `'HTTP/1.0'`, `'HTTP/1.1'` and `'HTTP/2'`
  94. versions. Custom protocols can define their own values as
  95. atoms.
  96. === Effective request URI
  97. The scheme, host, port, path and query string components
  98. of the effective request URI can all be retrieved directly:
  99. [source,erlang]
  100. ----
  101. #{
  102. scheme := Scheme,
  103. host := Host,
  104. port := Port,
  105. path := Path,
  106. qs := Qs
  107. } = Req.
  108. ----
  109. Or using the related functions:
  110. [source,erlang]
  111. Scheme = cowboy_req:scheme(Req),
  112. Host = cowboy_req:host(Req),
  113. Port = cowboy_req:port(Req),
  114. Path = cowboy_req:path(Req).
  115. Qs = cowboy_req:qs(Req).
  116. The scheme and host are lowercased case insensitive binary
  117. strings. The port is an integer representing the port number.
  118. The path and query string are case sensitive binary strings.
  119. Cowboy defines only the `<<"http">>` and `<<"https">>` schemes.
  120. They are chosen so that the scheme will only be `<<"https">>`
  121. for requests on secure HTTP/1.1 or HTTP/2 connections.
  122. // @todo Is that tested well?
  123. The effective request URI itself can be reconstructed with
  124. the `cowboy_req:uri/1,2` function. By default, an absolute
  125. URI is returned:
  126. [source,erlang]
  127. %% scheme://host[:port]/path[?qs]
  128. URI = cowboy_req:uri(Req).
  129. Options are available to either disable or replace some
  130. or all of the components. Various URIs or URI formats can
  131. be generated this way, including the origin form:
  132. [source,erlang]
  133. %% /path[?qs]
  134. URI = cowboy_req:uri(Req, #{host => undefined}).
  135. The protocol relative form:
  136. [source,erlang]
  137. %% //host[:port]/path[?qs]
  138. URI = cowboy_req:uri(Req, #{scheme => undefined}).
  139. The absolute URI without a query string:
  140. [source,erlang]
  141. URI = cowboy_req:uri(Req, #{qs => undefined}).
  142. A different host:
  143. [source,erlang]
  144. URI = cowboy_req:uri(Req, #{host => <<"example.org">>}).
  145. And any other combination.
  146. === Bindings
  147. // @todo Bindings should probably be a map themselves.
  148. Bindings are the host and path components that you chose
  149. to extract when defining the routes of your application.
  150. They are only available after the routing.
  151. Cowboy provides functions to retrieve one or all bindings.
  152. To retrieve a single value:
  153. [source,erlang]
  154. Value = cowboy_req:binding(userid, Req).
  155. When attempting to retrieve a value that was not bound,
  156. `undefined` will be returned. A different default value
  157. can be provided:
  158. [source,erlang]
  159. Value = cowboy_req:binding(userid, Req, 42).
  160. To retrieve everything that was bound:
  161. [source,erlang]
  162. Bindings = cowboy_req:bindings(Req).
  163. They are returned as a list of key/value pairs, with
  164. keys being atoms.
  165. // ...
  166. The Cowboy router also allows you to capture many host
  167. or path segments at once using the `...` qualifier.
  168. To retrieve the segments captured from the host name:
  169. [source,erlang]
  170. HostInfo = cowboy_req:host_info(Req).
  171. And the path segments:
  172. [source,erlang]
  173. PathInfo = cowboy_req:path_info(Req).
  174. Cowboy will return `undefined` if `...` was not used
  175. in the route.
  176. === Query parameters
  177. Cowboy provides two functions to access query parameters.
  178. You can use the first to get the entire list of parameters.
  179. [source,erlang]
  180. QsVals = cowboy_req:parse_qs(Req),
  181. {_, Lang} = lists:keyfind(<<"lang">>, 1, QsVals).
  182. Cowboy will only parse the query string, and not do any
  183. transformation. This function may therefore return duplicates,
  184. or parameter names without an associated value. The order of
  185. the list returned is undefined.
  186. When a query string is `key=1&key=2`, the list returned will
  187. contain two parameters of name `key`.
  188. The same is true when trying to use the PHP-style suffix `[]`.
  189. When a query string is `key[]=1&key[]=2`, the list returned will
  190. contain two parameters of name `key[]`.
  191. When a query string is simply `key`, Cowboy will return the
  192. list `[{<<"key">>, true}]`, using `true` to indicate that the
  193. parameter `key` was defined, but with no value.
  194. The second function Cowboy provides allows you to match out
  195. only the parameters you are interested in, and at the same
  196. time do any post processing you require using xref:constraints[constraints].
  197. This function returns a map.
  198. [source,erlang]
  199. #{id := ID, lang := Lang} = cowboy_req:match_qs([id, lang], Req).
  200. Constraints can be applied automatically. The following
  201. snippet will crash when the `id` parameter is not an integer,
  202. or when the `lang` parameter is empty. At the same time, the
  203. value for `id` will be converted to an integer term:
  204. [source,erlang]
  205. QsMap = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
  206. A default value may also be provided. The default will be used
  207. if the `lang` key is not found. It will not be used if
  208. the key is found but has an empty value.
  209. [source,erlang]
  210. #{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
  211. If no default is provided and the value is missing, the
  212. query string is deemed invalid and the process will crash.
  213. When the query string is `key=1&key=2`, the value for `key`
  214. will be the list `[1, 2]`. Parameter names do not need to
  215. include the PHP-style suffix. Constraints may be used to
  216. ensure that only one value was passed through.
  217. === Headers
  218. Header values can be retrieved either as a binary string
  219. or parsed into a more meaningful representation.
  220. The get the raw value:
  221. [source,erlang]
  222. HeaderVal = cowboy_req:header(<<"content-type">>, Req).
  223. Cowboy expects all header names to be provided as lowercase
  224. binary strings. This is true for both requests and responses,
  225. regardless of the underlying protocol.
  226. When the header is missing from the request, `undefined`
  227. will be returned. A different default can be provided:
  228. [source,erlang]
  229. HeaderVal = cowboy_req:header(<<"content-type">>, Req, <<"text/plain">>).
  230. All headers can be retrieved at once, either directly:
  231. [source,erlang]
  232. #{headers := AllHeaders} = Req.
  233. Or using a function:
  234. [source,erlang]
  235. AllHeaders = cowboy_req:headers(Req).
  236. Cowboy provides equivalent functions to parse individual
  237. headers. There is no function to parse all headers at once.
  238. To parse a specific header:
  239. [source,erlang]
  240. ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req).
  241. An exception will be thrown if it doesn't know how to parse the
  242. given header, or if the value is invalid. The list of known headers
  243. and default values can be found in the manual.
  244. When the header is missing, `undefined` is returned. You can
  245. change the default value. Note that it should be the parsed value
  246. directly:
  247. [source,erlang]
  248. ----
  249. ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req,
  250. {<<"text">>, <<"plain">>, []}).
  251. ----
  252. === Peer
  253. The peer address and port number for the connection can be
  254. retrieved either directly or using a function.
  255. To retrieve the peer directly:
  256. [source,erlang]
  257. #{peer := {IP, Port}} = Req.
  258. And using a function:
  259. [source,erlang]
  260. {IP, Port} = cowboy_req:peer(Req).
  261. Note that the peer corresponds to the remote end of the
  262. connection to the server, which may or may not be the
  263. client itself. It may also be a proxy or a gateway.