1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
::: Protocol upgrades
Cowboy features many different handlers, each for different purposes.
All handlers have a common entry point: the `init/2` function.
This function returns the name of the protocol that will be
used for processing the request, along with various options.
Cowboy defines four built-in handler types. Three of them are
implemented as sub protocols. More can be implemented by
writing a custom sub protocol.
The following table lists the built-in handler types.
|| Alias Module Description
|
| http - Plain HTTP handler
| long_polling cowboy_long_polling Long-polling handler
| rest cowboy_rest REST handler
| ws cowboy_websocket Websocket handler
Both the alias or the module name can be used to specify the
kind of handler. In addition, a user-defined module name can
be used.
``` erlang
init(Req, Opts) ->
{my_protocol, Req, Opts}.
```
The `init/2` function can also return some extra options for
handlers that are meant to be long running, for example the
`long_polling` and `ws` handler types. These options can also
be passed on to custom sub protocols. For example the following
`init/2` function defines both a timeout value and enables
process hibernation:
``` erlang
init(Req, Opts) ->
{my_protocol, Req, Opts, 5000, hibernate}.
```
It is up to the sub protocol to implement these (or reject
them if they are not supported).
The `cowboy_sub_protocol` behavior only requires one callback,
`upgrade/6`. It receives the Req object, the middleware environment,
the handler and options for this request, and the timeout and
hibernate values. The default timeout value is `infinity` and
the default hibernate value is `run`.
``` erlang
upgrade(Req, Env, Handler, HandlerOpts, Timeout, Hibernate) ->
%% ...
```
This callback is expected to behave like a middleware. Please
see the corresponding chapter for more information.
Sub protocols are expected to call the `cowboy_handler:terminate/5`
function when they terminate. This function will make sure that
the optional `terminate/3` callback will be called, if present.
|