cowboy_req.asciidoc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. = cowboy_req(3)
  2. == Name
  3. cowboy_req - HTTP request and response
  4. == Description
  5. The `cowboy_req` module provides functions to access, manipulate
  6. and respond to requests.
  7. The functions in this module follow patterns for their return types,
  8. based on the kind of function.
  9. * access: `Value`
  10. * action: `ok | {Result, Req} | {Result, Value, Req}`
  11. * modification: `Req`
  12. * question: `boolean()`
  13. Whenever `Req` is returned, you must use this returned value and
  14. ignore any previous you may have had. This value contains various
  15. values which are necessary for Cowboy to keep track of the request
  16. and response states.
  17. All functions which perform an action should only be called once.
  18. This includes reading the request body or replying. Cowboy will
  19. throw an error on the second call when it detects suspicious behavior.
  20. It is highly discouraged to pass the Req object to another process.
  21. Doing so and calling `cowboy_req` functions from it leads to
  22. undefined behavior.
  23. == Types
  24. === body_opts() = [Option]
  25. [source,erlang]
  26. ----
  27. Option = {continue, boolean()}
  28. | {length, non_neg_integer()}
  29. | {read_length, non_neg_integer()}
  30. | {read_timeout, timeout()}
  31. | {transfer_decode, transfer_decode_fun(), any()}
  32. | {content_decode, content_decode_fun()}
  33. ----
  34. Request body reading options.
  35. === cookie_opts() = [Option]
  36. [source,erlang]
  37. ----
  38. Option = {max_age, non_neg_integer()}
  39. | {domain, binary()}
  40. | {path, binary()}
  41. | {secure, boolean()}
  42. | {http_only, boolean()}
  43. ----
  44. Cookie options.
  45. === req() - opaque to the user
  46. The Req object.
  47. All functions in this module receive a `Req` as argument,
  48. and some of them return a new object labelled `Req2` in
  49. the function descriptions below.
  50. == Request related exports
  51. === binding(Name, Req) -> binding(Name, Req, undefined)
  52. Alias of `cowboy_req:binding/3`.
  53. === binding(Name, Req, Default) -> Value
  54. Name = atom():: Binding name.
  55. Default = any():: Default value.
  56. Value = any() | Default:: Binding value.
  57. Return the value for the given binding.
  58. By default the value is a binary, however constraints may change
  59. the type of this value (for example automatically converting
  60. numbers to integer).
  61. === bindings(Req) -> [{Name, Value}]
  62. Name = atom():: Binding name.
  63. Value = any():: Binding value.
  64. Return all bindings.
  65. By default the value is a binary, however constraints may change
  66. the type of this value (for example automatically converting
  67. numbers to integer).
  68. === header(Name, Req) -> header(Name, Req, undefined)
  69. Alias of `cowboy_req:header/3`.
  70. === header(Name, Req, Default) -> Value
  71. Name = binary():: Request header name.
  72. Default = any():: Default value.
  73. Value = binary() | Default:: Request header value.
  74. Return the value for the given header.
  75. While header names are case insensitive, this function expects
  76. the name to be a lowercase binary.
  77. === headers(Req) -> Headers
  78. Headers = cowboy:http_headers():: Request headers.
  79. Return all headers.
  80. === host(Req) -> Host
  81. Host = binary():: Requested host.
  82. Return the requested host.
  83. === host_info(Req) -> HostInfo
  84. HostInfo = cowboy_router:tokens() | undefined:: Extra tokens for the host.
  85. Return the extra tokens from matching against `...` during routing.
  86. === host_url(Req) -> HostURL
  87. HostURL = binary() | undefined:: Requested URL, without the path component.
  88. Return the requested URL excluding the path component.
  89. This function will always return `undefined` until the
  90. `cowboy_router` middleware has been executed.
  91. === match_cookies(Fields, Req) -> Map
  92. Fields = cowboy:fields():: Cookie fields match rules.
  93. Map = map():: Cookie fields matched.
  94. Match cookies against the given fields.
  95. Cowboy will only return the cookie values specified in the
  96. fields list, and ignore all others. Fields can be either
  97. the name of the cookie requested; the name along with a
  98. list of constraints; or the name, a list of constraints
  99. and a default value in case the cookie is missing.
  100. This function will crash if the cookie is missing and no
  101. default value is provided. This function will also crash
  102. if a constraint fails.
  103. The name of the cookie must be provided as an atom. The
  104. key of the returned map will be that atom. The value may
  105. be converted through the use of constraints, making this
  106. function able to extract, validate and convert values all
  107. in one step.
  108. === match_qs(Fields, Req) -> Map
  109. Fields = cowboy:fields():: Query string fields match rules.
  110. Map = map():: Query string fields matched.
  111. Match the query string against the given fields.
  112. Cowboy will only return the query string values specified
  113. in the fields list, and ignore all others. Fields can be
  114. either the key requested; the key along with a list of
  115. constraints; or the key, a list of constraints and a
  116. default value in case the key is missing.
  117. This function will crash if the key is missing and no
  118. default value is provided. This function will also crash
  119. if a constraint fails.
  120. The key must be provided as an atom. The key of the
  121. returned map will be that atom. The value may be converted
  122. through the use of constraints, making this function able
  123. to extract, validate and convert values all in one step.
  124. === meta(Name, Req) -> meta(Name, Req, undefined)
  125. Alias for `cowboy_req:meta/3`.
  126. === meta(Name, Req, Default) -> Value
  127. Name = atom():: Metadata name.
  128. Default = any():: Default value.
  129. Value = any():: Metadata value.
  130. Return metadata about the request.
  131. === method(Req) -> Method
  132. Method = binary():: Request method.
  133. Return the method.
  134. Methods are case sensitive. Standard methods are always uppercase.
  135. === parse_cookies(Req) -> [{Name, Value}]
  136. Name = binary():: Cookie name.
  137. Value = binary():: Cookie value.
  138. Parse and return all cookies.
  139. Cookie names are case sensitive.
  140. === parse_header(Name, Req) -> see below
  141. Alias of `cowboy_req:parse_header/3`.
  142. The `parse_header/2` function will call `parser_header/3` with a
  143. different default value depending on the header being parsed. The
  144. following table summarizes the default values used.
  145. [cols="<,^",options="header"]
  146. |===
  147. | Header name | Header value
  148. | content-length | `0`
  149. | cookie | `[]`
  150. | transfer-encoding | `[<<"identity">>]`
  151. | Any other header | `undefined`
  152. |===
  153. === parse_header(Name, Req, Default) -> ParsedValue | Default
  154. Name = binary():: Request header name.
  155. Default = any():: Default value.
  156. ParsedValue - see below:: Parsed request header value.
  157. Parse the given header.
  158. While header names are case insensitive, this function expects
  159. the name to be a lowercase binary.
  160. The parsed value differs depending on the header being parsed. The
  161. following table summarizes the different types returned.
  162. [cols="<,^",options="header"]
  163. |===
  164. | Header name | Type of parsed header value
  165. | accept | `[{{Type, SubType, Params}, Quality, AcceptExt}]`
  166. | accept-charset | `[{Charset, Quality}]`
  167. | accept-encoding | `[{Encoding, Quality}]`
  168. | accept-language | `[{LanguageTag, Quality}]`
  169. | authorization | `{AuthType, Credentials}`
  170. | content-length | `non_neg_integer()`
  171. | content-type | `{Type, SubType, ContentTypeParams}`
  172. | cookie | `[{binary(), binary()}]`
  173. | expect | `[Expect \| {Expect, ExpectValue, Params}]`
  174. | if-match | `'*' \| [{weak \| strong, OpaqueTag}]`
  175. | if-modified-since | `calendar:datetime()`
  176. | if-none-match | `'*' \| [{weak \| strong, OpaqueTag}]`
  177. | if-unmodified-since | `calendar:datetime()`
  178. | range | `{Unit, [Range]}`
  179. | sec-websocket-protocol | `[binary()]`
  180. | transfer-encoding | `[binary()]`
  181. | upgrade | `[binary()]`
  182. | x-forwarded-for | `[binary()]`
  183. |===
  184. Types for the above table:
  185. * Type = SubType = Charset = Encoding = LanguageTag = binary()
  186. * AuthType = Expect = OpaqueTag = Unit = binary()
  187. * Params = ContentTypeParams = [{binary(), binary()}]
  188. * Quality = 0..1000
  189. * AcceptExt = [{binary(), binary()} | binary()]
  190. * Credentials - see below
  191. * Range = {non_neg_integer(), non_neg_integer() | infinity} | neg_integer()
  192. The cookie names and values, the values of the sec-websocket-protocol
  193. and x-forwarded-for headers, the values in `AcceptExt` and `Params`,
  194. the authorization `Credentials`, the `ExpectValue` and `OpaqueTag`
  195. are case sensitive. All values in `ContentTypeParams` are case sensitive
  196. except the value of the charset parameter, which is case insensitive.
  197. All other values are case insensitive and will be returned as lowercase.
  198. The headers accept, accept-encoding and cookie headers can return
  199. an empty list. Some other headers are expected to have a value if provided
  200. and may crash if the value is missing.
  201. The authorization header parsing code currently only supports basic
  202. HTTP authentication. The `Credentials` type is thus `{Username, Password}`
  203. with `Username` and `Password` being `binary()`.
  204. The range header value `Range` can take three forms:
  205. * `{From, To}`: from `From` to `To` units
  206. * `{From, infinity}`: everything after `From` units
  207. * `-Final`: the final `Final` units
  208. An `undefined` tuple will be returned if Cowboy doesn't know how
  209. to parse the requested header.
  210. === parse_qs(Req) -> [{Name, Value}]
  211. Name = binary():: Query string field name.
  212. Value = binary() | true:: Query string field value.
  213. Return the request's query string as a list of tuples.
  214. The atom `true` is returned for keys which have no value.
  215. Keys with no value are different from keys with an empty
  216. value in that they do not have a `=` indicating the presence
  217. of a value.
  218. === path(Req) -> Path
  219. Path = binary():: Requested path.
  220. Return the requested path.
  221. === path_info(Req) -> PathInfo
  222. PathInfo = cowboy_router:tokens() | undefined:: Extra tokens for the path.
  223. Return the extra tokens from matching against `...` during routing.
  224. === peer(Req) -> Peer
  225. Peer = {inet:ip_address(), inet:port_number()}:: Peer IP address and port number.
  226. Return the client's IP address and port number.
  227. === port(Req) -> Port
  228. Port = inet:port_number():: Requested port number.
  229. Return the request's port.
  230. The port returned by this function is obtained by parsing
  231. the host header. It may be different than the actual port
  232. the client used to connect to the Cowboy server.
  233. === qs(Req) -> QueryString
  234. QueryString = binary():: Unprocessed query string.
  235. Return the request's query string.
  236. === set_meta(Name, Value, Req) -> Req2
  237. Name = atom():: Metadata name.
  238. Value = any():: Metadata value.
  239. Set metadata about the request.
  240. An existing value will be overwritten.
  241. === url(Req) -> URL
  242. URL = binary() | undefined:: Requested URL.
  243. Return the requested URL.
  244. This function will always return `undefined` until the
  245. `cowboy_router` middleware has been executed.
  246. === version(Req) -> Version
  247. Version = cowboy:http_version():: Client's advertised HTTP version.
  248. Return the HTTP version used for this request.
  249. == Request body related exports
  250. === body(Req) -> body(Req, [])
  251. Alias of `cowboy_req:body/2`.
  252. === body(Req, Opts) -> {ok, Data, Req2} | {more, Data, Req2}
  253. Opts = [body_opt()]:: Request body reading options.
  254. Data = binary():: Data read from the body.
  255. Read the request body.
  256. This function will read a chunk of the request body. If there is
  257. more data to be read after this function call, then a `more` tuple
  258. is returned. Otherwise an `ok` tuple is returned.
  259. Cowboy will automatically send a `100 Continue` reply if
  260. required. If this behavior is not desirable, it can be disabled
  261. by setting the `continue` option to `false`.
  262. Cowboy will by default attempt to read up to 8MB of the body,
  263. but in chunks of 1MB. It will use a timeout of 15s per chunk.
  264. All these values can be changed using the `length`, `read_length`
  265. and `read_timeout` options respectively. Note that the size
  266. of the data may not be the same as requested as the decoding
  267. functions may grow or shrink it, and Cowboy makes not attempt
  268. at returning an exact amount.
  269. Cowboy will properly handle chunked transfer-encoding by
  270. default. If any other transfer-encoding or content-encoding
  271. has been used for the request, custom decoding functions
  272. can be used. The `content_decode` and `transfer_decode`
  273. options allow setting the decode functions manually.
  274. After the body has been streamed fully, Cowboy will remove
  275. the transfer-encoding header from the Req object, and add
  276. the content-length header if it wasn't already there.
  277. This function can only be called once. Cowboy will not cache
  278. the result of this call.
  279. === body_length(Req) -> Length
  280. Length = non_neg_integer() | undefined:: Length of the request body.
  281. Return the length of the request body.
  282. The length will only be returned if the request does not
  283. use any transfer-encoding and if the content-length header
  284. is present.
  285. === body_qs(Req) -> body_qs(Req, [{length, 64000}, {read_length, 64000}, {read_timeout, 5000}])
  286. Alias of `cowboy_req:body_qs/2`.
  287. === body_qs(Req, Opts) -> {ok, [{Name, Value}], Req2} | {badlength, Req2}
  288. Opts = [body_opt()]:: Request body reading options.
  289. Name = binary():: Field name.
  290. Value = binary() | true:: Field value.
  291. Return the request body as a list of tuples.
  292. This function will parse the body assuming the content-type
  293. application/x-www-form-urlencoded, commonly used for the
  294. query string.
  295. This function calls `body/2` for reading the body, with the
  296. same options it received. By default it will attempt to read
  297. a body of 64KB in one chunk, with a timeout of 5s. If the
  298. body is larger then a `badlength` tuple is returned.
  299. This function can only be called once. Cowboy will not cache
  300. the result of this call.
  301. === has_body(Req) -> boolean()
  302. Return whether the request has a body.
  303. === part(Req) -> part(Req, [{length, 64000}, {read_length, 64000}, {read_timeout, 5000}])
  304. Alias of `cowboy_req:part/2`.
  305. === part(Req, Opts) -> {ok, Headers, Req2} | {done, Req2}
  306. Opts = [body_opt()]:: Request body reading options.
  307. Headers = cow_multipart:headers():: Part's headers.
  308. Read the headers for the next part of the multipart message.
  309. Cowboy will skip any data remaining until the beginning of
  310. the next part. This includes the preamble to the multipart
  311. message but also the body of a previous part if it hasn't
  312. been read. Both are skipped automatically when calling this
  313. function.
  314. The headers returned are MIME headers, NOT HTTP headers.
  315. They can be parsed using the functions from the `cow_multipart`
  316. module. In addition, the `cow_multipart:form_data/1` function
  317. can be used to quickly figure out `multipart/form-data` messages.
  318. It takes the list of headers and returns whether this part is
  319. a simple form field or a file being uploaded.
  320. Note that once a part has been read, or skipped, it cannot
  321. be read again.
  322. This function calls `body/2` for reading the body, with the
  323. same options it received. By default it will only read chunks
  324. of 64KB with a timeout of 5s. This is tailored for reading
  325. part headers, not for skipping the previous part's body.
  326. You might want to consider skipping large parts manually.
  327. === part_body(Req) -> part_body(Req, [])
  328. Alias of `cowboy_req:part_body/2`.
  329. === part_body(Req, Opts) -> {ok, Data, Req2} | {more, Data, Req2}
  330. Opts = [body_opt()]:: Request body reading options.
  331. Data = binary():: Part's body.
  332. Read the body of the current part of the multipart message.
  333. This function calls `body/2` for reading the body, with the
  334. same options it received. It uses the same defaults.
  335. If there are more data to be read from the socket for this
  336. part, the function will return what it could read inside a
  337. `more` tuple. Otherwise, it will return an `ok` tuple.
  338. Calling this function again after receiving a `more` tuple
  339. will return another chunk of body. The last chunk will be
  340. returned inside an `ok` tuple.
  341. Note that once the body has been read, fully or partially,
  342. it cannot be read again.
  343. == Response related exports
  344. === chunk(Data, Req) -> ok
  345. Data = iodata():: Chunk data to be sent.
  346. Send a chunk of data.
  347. This function should be called as many times as needed
  348. to send data chunks after calling `chunked_reply/{2,3}`.
  349. When the method is HEAD, no data will actually be sent.
  350. If the request uses HTTP/1.0, the data is sent directly
  351. without wrapping it in an HTTP/1.1 chunk, providing
  352. compatibility with older clients.
  353. === chunked_reply(StatusCode, Req) -> chunked_reply(StatusCode, [], Req)
  354. Alias of `cowboy_req:chunked_reply/3`.
  355. === chunked_reply(StatusCode, Headers, Req) -> Req2
  356. StatusCode = cowboy:http_status():: Response status code.
  357. Headers = cowboy:http_headers():: Response headers.
  358. Send a response using chunked transfer-encoding.
  359. This function effectively sends the response status line
  360. and headers to the client.
  361. This function will not send any body set previously. After
  362. this call the handler must use the `chunk/2` function
  363. repeatedly to send the body in as many chunks as needed.
  364. If the request uses HTTP/1.0, the data is sent directly
  365. without wrapping it in an HTTP/1.1 chunk, providing
  366. compatibility with older clients.
  367. This function can only be called once, with the exception
  368. of overriding the response in the `onresponse` hook.
  369. === continue(Req) -> ok
  370. Send a 100 Continue intermediate reply.
  371. This reply is required before the client starts sending the
  372. body when the request contains the `expect` header with the
  373. `100-continue` value.
  374. Cowboy will send this automatically when required. However
  375. you may want to do it manually by disabling this behavior
  376. with the `continue` body option and then calling this
  377. function.
  378. === delete_resp_header(Name, Req) -> Req2
  379. Name = binary():: Response header name.
  380. Delete the given response header.
  381. While header names are case insensitive, this function expects
  382. the name to be a lowercase binary.
  383. === has_resp_body(Req) -> boolean()
  384. Return whether a response body has been set.
  385. This function will return false if a response body has
  386. been set with a length of 0.
  387. === has_resp_header(Name, Req) -> boolean()
  388. Name = binary():: Response header name.
  389. Return whether the given response header has been set.
  390. While header names are case insensitive, this function expects
  391. the name to be a lowercase binary.
  392. === reply(StatusCode, Req) -> reply(StatusCode, [], Req)
  393. Alias of `cowboy_req:reply/3`.
  394. === reply(StatusCode, Headers, Req) - see below
  395. Alias of `cowboy_req:reply/4`, with caveats.
  396. === reply(StatusCode, Headers, Body, Req) -> Req2
  397. StatusCode = cowboy:http_status():: Response status code.
  398. Headers = cowboy:http_headers():: Response headers.
  399. Body = iodata():: Response body.
  400. Send a response.
  401. This function effectively sends the response status line,
  402. headers and body to the client, in a single send function
  403. call.
  404. The `reply/2` and `reply/3` functions will send the body
  405. set previously, if any. The `reply/4` function overrides
  406. any body set previously and sends `Body` instead.
  407. If a body function was set, and `reply/2` or `reply/3` was
  408. used, it will be called before returning.
  409. No more data can be sent to the client after this function
  410. returns.
  411. This function can only be called once, with the exception
  412. of overriding the response in the `onresponse` hook.
  413. === set_resp_body(Body, Req) -> Req2
  414. Body = iodata():: Response body.
  415. Set a response body.
  416. This body will not be sent if `chunked_reply/{2,3}` or
  417. `reply/4` is used, as they override it.
  418. === set_resp_body_fun(Fun, Req) -> Req2
  419. Alias of `cowboy_req:set_resp_body_fun/3`.
  420. === set_resp_body_fun(Length, Fun, Req) -> Req2
  421. Fun = fun((Socket, Transport) -> ok):: Fun that will send the response body.
  422. Socket = inet:socket():: Socket for this connection.
  423. Transport = module():: Transport module for this socket.
  424. Length = non_neg_integer():: Length of the response body.
  425. Set a fun for sending the response body.
  426. If a `Length` is provided, it will be sent in the
  427. content-length header in the response. It is recommended
  428. to set the length if it can be known in advance. Otherwise,
  429. the transfer-encoding header will be set to identity.
  430. This function will only be called if the response is sent
  431. using the `reply/2` or `reply/3` function.
  432. The fun will receive the Ranch `Socket` and `Transport` as
  433. arguments. Only send and sendfile operations are supported.
  434. === set_resp_body_fun(chunked, Fun, Req) -> Req2
  435. Fun = fun((ChunkFun) -> ok):: Fun that will send the response body.
  436. ChunkFun = fun((iodata()) -> ok):: Fun to call for every chunk to be sent.
  437. Set a fun for sending the response body using chunked transfer-encoding.
  438. This function will only be called if the response is sent
  439. using the `reply/2` or `reply/3` function.
  440. The fun will receive another fun as argument. This fun is to
  441. be used to send chunks in a similar way to the `chunk/2` function,
  442. except the fun only takes one argument, the data to be sent in
  443. the chunk.
  444. === set_resp_cookie(Name, Value, Opts, Req) -> Req2
  445. Name = iodata():: Cookie name.
  446. Value = iodata():: Cookie value.
  447. Opts = cookie_opts():: Cookie options.
  448. Set a cookie in the response.
  449. Cookie names are case sensitive.
  450. === set_resp_header(Name, Value, Req) -> Req2
  451. Name = binary():: Response header name.
  452. Value = iodata():: Response header value.
  453. Set a response header.
  454. You should use `set_resp_cookie/4` instead of this function
  455. to set cookies.