hooks.ezdoc 1.3 KB

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