middlewares.ezdoc 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. ::: Middlewares
  2. Cowboy delegates the request processing to middleware components.
  3. By default, two middlewares are defined, for the routing and handling
  4. of the request, as is detailed in most of this guide.
  5. Middlewares give you complete control over how requests are to be
  6. processed. You can add your own middlewares to the mix or completely
  7. change the chain of middlewares as needed.
  8. Cowboy will execute all middlewares in the given order, unless one
  9. of them decides to stop processing.
  10. :: Usage
  11. Middlewares only need to implement a single callback: `execute/2`.
  12. It is defined in the `cowboy_middleware` behavior.
  13. This callback has two arguments. The first is the `Req` object.
  14. The second is the environment.
  15. Middlewares can return one of four different values:
  16. * `{ok, Req, Env}` to continue the request processing
  17. * `{suspend, Module, Function, Args}` to hibernate
  18. * `{stop, Req}` to stop processing and move on to the next request
  19. Of note is that when hibernating, processing will resume on the given
  20. MFA, discarding all previous stacktrace. Make sure you keep the `Req`
  21. and `Env` in the arguments of this MFA for later use.
  22. If an error happens during middleware processing, Cowboy will not try
  23. to send an error back to the socket, the process will just crash. It
  24. is up to the middleware to make sure that a reply is sent if something
  25. goes wrong.
  26. :: Configuration
  27. The middleware environment is defined as the `env` protocol option.
  28. In the previous chapters we saw it briefly when we needed to pass
  29. the routing information. It is a list of tuples with the first
  30. element being an atom and the second any Erlang term.
  31. Two values in the environment are reserved:
  32. * `listener` contains the name of the listener
  33. * `result` contains the result of the processing
  34. The `listener` value is always defined. The `result` value can be
  35. set by any middleware. If set to anything other than `ok`, Cowboy
  36. will not process any subsequent requests on this connection.
  37. The middlewares that come with Cowboy may define or require other
  38. environment values to perform.
  39. You can update the environment by calling the `cowboy:set_env/3`
  40. convenience function, adding or replacing a value in the environment.
  41. :: Routing middleware
  42. The routing middleware requires the `dispatch` value. If routing
  43. succeeds, it will put the handler name and options in the `handler`
  44. and `handler_opts` values of the environment, respectively.
  45. :: Handler middleware
  46. The handler middleware requires the `handler` and `handler_opts`
  47. values. It puts the result of the request handling into `result`.