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