hooks.asciidoc 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. [[hooks]]
  2. == Hooks
  3. Hooks allow the user to customize Cowboy's behavior during specific
  4. operations.
  5. === Onresponse
  6. The `onresponse` hook is called right before sending the response
  7. to the socket. It can be used for the purposes of logging responses,
  8. or for modifying the response headers or body. The best example is
  9. providing custom error pages.
  10. Note that this function MUST NOT crash. Cowboy may or may not send a
  11. reply if this function crashes. If a reply is sent, the hook MUST
  12. explicitly provide all headers that are needed.
  13. You can specify the `onresponse` hook when creating the listener.
  14. [source,erlang]
  15. ----
  16. cowboy:start_http(my_http_listener, 100,
  17. [{port, 8080}],
  18. [
  19. {env, [{dispatch, Dispatch}]},
  20. {onresponse, fun ?MODULE:custom_404_hook/4}
  21. ]
  22. ).
  23. ----
  24. The following hook function will provide a custom body for 404 errors
  25. when it has not been provided before, and will let Cowboy proceed with
  26. the default response otherwise.
  27. [source,erlang]
  28. ----
  29. custom_404_hook(404, Headers, <<>>, Req) ->
  30. Body = <<"404 Not Found.">>,
  31. Headers2 = lists:keyreplace(<<"content-length">>, 1, Headers,
  32. {<<"content-length">>, integer_to_list(byte_size(Body))}),
  33. cowboy_req:reply(404, Headers2, Body, Req);
  34. custom_404_hook(_, _, _, Req) ->
  35. Req.
  36. ----
  37. Again, make sure to always return the last request object obtained.