| 1 |
= cowboy_handler(3) |
| 2 |
|
| 3 |
== Name |
| 4 |
|
| 5 |
cowboy_handler - Plain HTTP handlers |
| 6 |
|
| 7 |
== Description |
| 8 |
|
| 9 |
The `cowboy_handler` middleware executes the handler selected |
| 10 |
by the router or any other preceding middleware. |
| 11 |
|
| 12 |
This middleware takes the handler module and initial state |
| 13 |
from the `handler` and `handler_opts` environment values, |
| 14 |
respectively. On completion, it adds a `result` value to |
| 15 |
the middleware environment, containing the return value |
| 16 |
of the `terminate/3` callback (if defined) and `ok` otherwise. |
| 17 |
|
| 18 |
This module also defines a callback interface for handling |
| 19 |
HTTP requests. |
| 20 |
|
| 21 |
== Callbacks |
| 22 |
|
| 23 |
Plain HTTP handlers implement the following interface: |
| 24 |
|
| 25 |
[source,erlang] |
| 26 |
---- |
| 27 |
init(Req, State) -> {ok, Req, State} |
| 28 |
|
| 29 |
terminate(Reason, Req, State) -> ok %% optional |
| 30 |
|
| 31 |
Req :: cowboy_req:req() |
| 32 |
State :: any() |
| 33 |
Reason :: normal |
| 34 |
| {crash, error | exit | throw, any()} |
| 35 |
---- |
| 36 |
|
| 37 |
These two callbacks are common to all handlers. |
| 38 |
|
| 39 |
Plain HTTP handlers do all their work in the `init/2` |
| 40 |
callback. Returning `ok` terminates the handler. If no |
| 41 |
response is sent, Cowboy will send a `204 No Content`. |
| 42 |
|
| 43 |
The optional `terminate/3` callback will ultimately be called |
| 44 |
with the reason for the termination of the handler. |
| 45 |
Cowboy will terminate the process right after this. There |
| 46 |
is no need to perform any cleanup in this callback. |
| 47 |
|
| 48 |
The following terminate reasons are defined for plain HTTP |
| 49 |
handlers: |
| 50 |
|
| 51 |
normal:: |
| 52 |
The connection was closed normally. |
| 53 |
|
| 54 |
{crash, Class, Reason}:: |
| 55 |
A crash occurred in the handler. `Class` and `Reason` can be |
| 56 |
used to obtain more information about the crash. |
| 57 |
|
| 58 |
== Exports |
| 59 |
|
| 60 |
The following function should be called by modules implementing |
| 61 |
custom handlers to execute the optional terminate callback: |
| 62 |
|
| 63 |
* link:man:cowboy_handler:terminate(3)[cowboy_handler:terminate(3)] - Terminate the handler |
| 64 |
|
| 65 |
== See also |
| 66 |
|
| 67 |
link:man:cowboy(7)[cowboy(7)] |