| 1 |
= cowboy_loop(3) |
| 2 |
|
| 3 |
== Name |
| 4 |
|
| 5 |
cowboy_loop - Loop handlers |
| 6 |
|
| 7 |
== Description |
| 8 |
|
| 9 |
The module `cowboy_loop` defines a callback interface for |
| 10 |
long running HTTP connections. |
| 11 |
|
| 12 |
You should switch to this behavior for long polling, |
| 13 |
server-sent events and similar long-running requests. |
| 14 |
|
| 15 |
There are generally two usage patterns: |
| 16 |
|
| 17 |
* Loop until receiving a specific message, then send |
| 18 |
a response and stop execution (for example long polling); |
| 19 |
|
| 20 |
* Or initiate a response in `init/2` and stream the |
| 21 |
body in `info/3` as necessary (for example server-sent events). |
| 22 |
|
| 23 |
== Callbacks |
| 24 |
|
| 25 |
Loop handlers implement the following interface: |
| 26 |
|
| 27 |
[source,erlang] |
| 28 |
---- |
| 29 |
init(Req, State) |
| 30 |
-> {cowboy_loop, Req, State} |
| 31 |
| {cowboy_loop, Req, State, hibernate | timeout()} |
| 32 |
|
| 33 |
info(Info, Req, State) |
| 34 |
-> {ok, Req, State} |
| 35 |
| {ok, Req, State, hibernate | timeout()} |
| 36 |
| {stop, Req, State} |
| 37 |
|
| 38 |
terminate(Reason, Req, State) -> ok %% optional |
| 39 |
|
| 40 |
Req :: cowboy_req:req() |
| 41 |
State :: any() |
| 42 |
Info :: any() |
| 43 |
Reason :: stop |
| 44 |
| {crash, error | exit | throw, any()} |
| 45 |
---- |
| 46 |
|
| 47 |
The `init/2` callback is common to all handlers. To switch |
| 48 |
to the loop behavior, it must return `cowboy_loop` as the |
| 49 |
first element of the tuple. |
| 50 |
|
| 51 |
The `info/3` callback will be called for every Erlang message |
| 52 |
received. It may choose to continue the receive loop or stop |
| 53 |
it. |
| 54 |
|
| 55 |
The optional `terminate/3` callback will ultimately be called |
| 56 |
with the reason for the termination of the handler. |
| 57 |
Cowboy will terminate the process right after this. There |
| 58 |
is no need to perform any cleanup in this callback. |
| 59 |
|
| 60 |
The following terminate reasons are defined for loop handlers: |
| 61 |
|
| 62 |
stop:: |
| 63 |
The handler requested to close the connection by returning |
| 64 |
a `stop` tuple. |
| 65 |
|
| 66 |
{crash, Class, Reason}:: |
| 67 |
A crash occurred in the handler. `Class` and `Reason` can be |
| 68 |
used to obtain more information about the crash. |
| 69 |
|
| 70 |
== Changelog |
| 71 |
|
| 72 |
* *2.11*: A timeout may be returned instead of `hibernate`. |
| 73 |
It functions the same way as the `gen_server` timeout. |
| 74 |
* *2.0*: Loop handlers no longer need to handle socket events. |
| 75 |
* *1.0*: Behavior introduced. |
| 76 |
|
| 77 |
== See also |
| 78 |
|
| 79 |
link:man:cowboy(7)[cowboy(7)], |
| 80 |
link:man:cowboy_handler(3)[cowboy_handler(3)] |