Debian Codegraph @

doc/src/guide/resp.asciidoc

raw
1 [[resp]]
2 == Sending a response
3
4 The response must be sent using the Req object.
5
6 Cowboy provides two different ways of sending responses:
7 either directly or by streaming the body. Response headers
8 and body may be set in advance. The response is sent as
9 soon as one of the reply or stream reply function is
10 called.
11
12 Cowboy also provides a simplified interface for sending
13 files. It can also send only specific parts of a file.
14
15 While only one response is allowed for every request,
16 HTTP/2 introduced a mechanism that allows the server
17 to push additional resources related to the response.
18 This chapter also describes how this feature works in
19 Cowboy.
20
21 === Reply
22
23 Cowboy provides three functions for sending the entire reply,
24 depending on whether you need to set headers and body. In all
25 cases, Cowboy will add any headers required by the protocol
26 (for example the date header will always be sent).
27
28 When you need to set only the status code,
29 use `cowboy_req:reply/2`:
30
31 [source,erlang]
32 Req = cowboy_req:reply(200, Req0).
33
34 When you need to set response headers at the same time,
35 use `cowboy_req:reply/3`:
36
37 [source,erlang]
38 ----
39 Req = cowboy_req:reply(303, #{
40 <<"location">> => <<"https://ninenines.eu">>
41 }, Req0).
42 ----
43
44 Note that the header name must always be a lowercase
45 binary.
46
47 When you also need to set the response body,
48 use `cowboy_req:reply/4`:
49
50 [source,erlang]
51 ----
52 Req = cowboy_req:reply(200, #{
53 <<"content-type">> => <<"text/plain">>
54 }, "Hello world!", Req0).
55 ----
56
57 You should always set the content-type header when the
58 response has a body. There is however no need to set
59 the content-length header; Cowboy does it automatically.
60
61 The response body and the header values must be either
62 a binary or an iolist. An iolist is a list containing
63 binaries, characters, strings or other iolists. This
64 allows you to build a response from different parts
65 without having to do any concatenation:
66
67 [source,erlang]
68 ----
69 Title = "Hello world!",
70 Body = <<"Hats off!">>,
71 Req = cowboy_req:reply(200, #{
72 <<"content-type">> => <<"text/html">>
73 }, ["<html><head><title>", Title, "</title></head>",
74 "<body><p>", Body, "</p></body></html>"], Req0).
75 ----
76
77 This method of building responses is more efficient than
78 concatenating. Behind the scenes, each element of the list
79 is simply a pointer, and those pointers are used directly
80 when writing to the socket.
81
82 === Stream reply
83
84 Cowboy provides two functions for initiating a response,
85 and an additional function for streaming the response body.
86 Cowboy will add any required headers to the response.
87
88 // @todo For HTTP/1.1 Cowboy should probably not use chunked transfer-encoding if the content-length is set.
89
90 When you need to set only the status code,
91 use `cowboy_req:stream_reply/2`:
92
93 [source,erlang]
94 ----
95 Req = cowboy_req:stream_reply(200, Req0),
96
97 cowboy_req:stream_body("Hello...", nofin, Req),
98 cowboy_req:stream_body("chunked...", nofin, Req),
99 cowboy_req:stream_body("world!!", fin, Req).
100 ----
101
102 The second argument to `cowboy_req:stream_body/3` indicates
103 whether this data terminates the body. Use `fin` for the
104 final flag, and `nofin` otherwise.
105
106 This snippet does not set a content-type header. This is
107 not recommended. All responses with a body should have
108 a content-type. The header can be set beforehand, or
109 using the `cowboy_req:stream_reply/3`:
110
111 [source,erlang]
112 ----
113 Req = cowboy_req:stream_reply(200, #{
114 <<"content-type">> => <<"text/html">>
115 }, Req0),
116
117 cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
118 cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", fin, Req).
119 ----
120
121 HTTP provides a few different ways to stream response bodies.
122 Cowboy will select the most appropriate one based on the HTTP
123 version and the request and response headers.
124
125 While not required by any means, it is recommended that you
126 set the content-length header in the response if you know it
127 in advance. This will ensure that the best response method
128 is selected and help clients understand when the response
129 is fully received.
130
131 Cowboy also provides a function to send response trailers.
132 Response trailers are semantically equivalent to the headers
133 you send in the response, only they are sent at the end.
134 This is especially useful to attach information to the
135 response that could not be generated until the response
136 body was fully generated.
137
138 Trailer fields must be listed in the trailer header. Any
139 field not listed might be dropped by the client or an intermediary.
140
141 [source,erlang]
142 ----
143 Req = cowboy_req:stream_reply(200, #{
144 <<"content-type">> => <<"text/html">>,
145 <<"trailer">> => <<"expires, content-md5">>
146 }, Req0),
147
148 cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
149 cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", nofin, Req),
150
151 cowboy_req:stream_trailers(#{
152 <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
153 <<"content-md5">> => <<"c6081d20ff41a42ce17048ed1c0345e2">>
154 }, Req).
155 ----
156
157 The stream ends with trailers. It is no longer possible to
158 send data after sending trailers. You cannot send trailers
159 after setting the `fin` flag when streaming the body.
160
161 === Preset response headers
162
163 Cowboy provides functions to set response headers without
164 immediately sending them. They are stored in the Req object
165 and sent as part of the response when a reply function is
166 called.
167
168 To set response headers:
169
170 [source,erlang]
171 Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
172
173 Header names must be a lowercase binary.
174
175 Do not use this function for setting cookies. Refer to
176 the xref:cookies[Cookies] chapter for more information.
177
178 To check if a response header has already been set:
179
180 [source,erlang]
181 cowboy_req:has_resp_header(<<"allow">>, Req).
182
183 It returns `true` if the header was set, `false` otherwise.
184
185 To delete a response header that was set previously:
186
187 [source,erlang]
188 Req = cowboy_req:delete_resp_header(<<"allow">>, Req0).
189
190 === Overriding headers
191
192 As Cowboy provides different ways of setting response
193 headers and body, clashes may occur, so it's important
194 to understand what happens when a header is set twice.
195
196 Headers come from five different origins:
197
198 * Protocol-specific headers (for example HTTP/1.1's connection header)
199 * Other required headers (for example the date header)
200 * Preset headers
201 * Headers given to the reply function
202 * Set-cookie headers
203
204 Cowboy does not allow overriding protocol-specific headers.
205
206 Set-cookie headers will always be appended at the end of
207 the list of headers before sending the response.
208
209 Headers given to the reply function will always override
210 preset headers and required headers. If a header is found
211 in two or three of these, then the one in the reply function
212 is picked and the others are dropped.
213
214 Similarly, preset headers will always override required
215 headers.
216
217 To illustrate, look at the following snippet. Cowboy by
218 default sends the server header with the value "Cowboy".
219 We can override it:
220
221 [source,erlang]
222 ----
223 Req = cowboy_req:reply(200, #{
224 <<"server">> => <<"yaws">>
225 }, Req0).
226 ----
227
228 === Preset response body
229
230 Cowboy provides functions to set the response body without
231 immediately sending it. It is stored in the Req object and
232 sent when the reply function is called.
233
234 To set the response body:
235
236 [source,erlang]
237 Req = cowboy_req:set_resp_body("Hello world!", Req0).
238
239 // @todo Yeah we probably should add that function that
240 // also sets the content-type at the same time...
241
242 To check if a response body has already been set:
243
244 [source,erlang]
245 cowboy_req:has_resp_body(Req).
246
247 It returns `true` if the body was set and is non-empty,
248 `false` otherwise.
249
250 // @todo We probably should also have a function that
251 // properly removes the response body, including any
252 // content-* headers.
253
254 The preset response body is only sent if the reply function
255 used is `cowboy_req:reply/2` or `cowboy_req:reply/3`.
256
257 === Sending files
258
259 Cowboy provides a shortcut for sending files. When
260 using `cowboy_req:reply/4`, or when presetting the
261 response header, you can give a `sendfile` tuple to
262 Cowboy:
263
264 [source,erlang]
265 {sendfile, Offset, Length, Filename}
266
267 Depending on the values for `Offset` or `Length`, the
268 entire file may be sent, or just a part of it.
269
270 The length is required even for sending the entire file.
271 Cowboy sends it in the content-length header.
272
273 To send a file while replying:
274
275 [source,erlang]
276 ----
277 Req = cowboy_req:reply(200, #{
278 <<"content-type">> => "image/png"
279 }, {sendfile, 0, 12345, "path/to/logo.png"}, Req0).
280 ----
281
282 // @todo An example of presetting a file would be useful,
283 // but let's wait for the function that can set the
284 // content-type at the same time.
285
286 // @todo What about streaming many files? For example
287 // it should be possible to build a tar file on the fly
288 // while still using sendfile. Another example could be
289 // proper support for multipart byte ranges. Yet another
290 // example would be automatic concatenation of CSS or JS
291 // files.
292
293 === Informational responses
294
295 Cowboy allows you to send informational responses.
296
297 Informational responses are responses that have a status
298 code between 100 and 199. Any number can be sent before
299 the proper response. Sending an informational response
300 does not change the behavior of the proper response, and
301 clients are expected to ignore any informational response
302 they do not understand.
303
304 The following snippet sends a 103 informational response
305 with some headers that are expected to be in the final
306 response.
307
308 [source,erlang]
309 ----
310 Req = cowboy_req:inform(103, #{
311 <<"link">> => <<"</style.css>; rel=preload; as=style, </script.js>; rel=preload; as=script">>
312 }, Req0).
313 ----
314
315 === Push
316
317 The HTTP/2 protocol introduced the ability to push resources
318 related to the one sent in the response. Cowboy provides two
319 functions for that purpose: `cowboy_req:push/3,4`.
320
321 Push is only available for HTTP/2. Cowboy will automatically
322 ignore push requests if the protocol doesn't support it.
323
324 The push function must be called before any of the reply
325 functions. Doing otherwise will result in a crash.
326
327 To push a resource, you need to provide the same information
328 as a client performing a request would. This includes the
329 HTTP method, the URI and any necessary request headers.
330
331 Cowboy by default only requires you to give the path to
332 the resource and the request headers. The rest of the URI
333 is taken from the current request (excluding the query
334 string, set to empty) and the method is GET by default.
335
336 The following snippet pushes a CSS file that is linked to
337 in the response:
338
339 [source,erlang]
340 ----
341 cowboy_req:push("/static/style.css", #{
342 <<"accept">> => <<"text/css">>
343 }, Req0),
344 Req = cowboy_req:reply(200, #{
345 <<"content-type">> => <<"text/html">>
346 }, ["<html><head><title>My web page</title>",
347 "<link rel='stylesheet' type='text/css' href='/static/style.css'>",
348 "<body><p>Welcome to Erlang!</p></body></html>"], Req0).
349 ----
350
351 To override the method, scheme, host, port or query string,
352 simply pass in a fourth argument. The following snippet
353 uses a different host name:
354
355 [source,erlang]
356 ----
357 cowboy_req:push("/static/style.css", #{
358 <<"accept">> => <<"text/css">>
359 }, #{host => <<"cdn.example.org">>}, Req),
360 ----
361
362 Pushed resources don't have to be files. As long as the push
363 request is cacheable, safe and does not include a body, the
364 resource can be pushed.
365
366 Under the hood, Cowboy handles pushed requests the same as
367 normal requests: a different process is created which will
368 ultimately send a response to the client.