2016-01-14 13:35:25 +01:00
|
|
|
[[hooks]]
|
|
|
|
== Hooks
|
2013-01-01 18:27:41 +01:00
|
|
|
|
2014-09-24 14:39:17 +03:00
|
|
|
Hooks allow the user to customize Cowboy's behavior during specific
|
|
|
|
operations.
|
2013-01-01 18:27:41 +01:00
|
|
|
|
2016-01-14 13:35:25 +01:00
|
|
|
=== Onresponse
|
2013-01-01 18:27:41 +01:00
|
|
|
|
2013-01-18 00:54:41 +01:00
|
|
|
The `onresponse` hook is called right before sending the response
|
|
|
|
to the socket. It can be used for the purposes of logging responses,
|
|
|
|
or for modifying the response headers or body. The best example is
|
|
|
|
providing custom error pages.
|
|
|
|
|
2014-09-24 14:39:17 +03:00
|
|
|
Note that this function MUST NOT crash. Cowboy may or may not send a
|
|
|
|
reply if this function crashes. If a reply is sent, the hook MUST
|
|
|
|
explicitly provide all headers that are needed.
|
2013-01-18 00:54:41 +01:00
|
|
|
|
2014-06-25 11:23:58 +02:00
|
|
|
You can specify the `onresponse` hook when creating the listener.
|
2013-01-18 00:54:41 +01:00
|
|
|
|
2016-01-14 13:35:25 +01:00
|
|
|
[source,erlang]
|
|
|
|
----
|
2013-01-18 00:54:41 +01:00
|
|
|
cowboy:start_http(my_http_listener, 100,
|
|
|
|
[{port, 8080}],
|
|
|
|
[
|
|
|
|
{env, [{dispatch, Dispatch}]},
|
|
|
|
{onresponse, fun ?MODULE:custom_404_hook/4}
|
|
|
|
]
|
|
|
|
).
|
2016-01-14 13:35:25 +01:00
|
|
|
----
|
2013-01-18 00:54:41 +01:00
|
|
|
|
|
|
|
The following hook function will provide a custom body for 404 errors
|
|
|
|
when it has not been provided before, and will let Cowboy proceed with
|
|
|
|
the default response otherwise.
|
|
|
|
|
2016-01-14 13:35:25 +01:00
|
|
|
[source,erlang]
|
|
|
|
----
|
2013-01-18 00:54:41 +01:00
|
|
|
custom_404_hook(404, Headers, <<>>, Req) ->
|
2013-03-01 18:02:33 -06:00
|
|
|
Body = <<"404 Not Found.">>,
|
|
|
|
Headers2 = lists:keyreplace(<<"content-length">>, 1, Headers,
|
|
|
|
{<<"content-length">>, integer_to_list(byte_size(Body))}),
|
2014-09-23 16:43:29 +03:00
|
|
|
cowboy_req:reply(404, Headers2, Body, Req);
|
2013-01-18 00:54:41 +01:00
|
|
|
custom_404_hook(_, _, _, Req) ->
|
|
|
|
Req.
|
2016-01-14 13:35:25 +01:00
|
|
|
----
|
2013-01-18 00:54:41 +01:00
|
|
|
|
|
|
|
Again, make sure to always return the last request object obtained.
|