sub_protocols.ezdoc 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. ::: Sub protocols
  2. Sub protocols are used for creating new types of handlers that
  3. provide extra functionality in a reusable way. Cowboy uses this
  4. mechanism to provide its loop, REST and Websocket handlers.
  5. This chapter will explain how to create your own sub protocols
  6. and handler types.
  7. :: Usage
  8. To switch to a sub protocol, the `init/2` callback must return
  9. the name of the sub protocol module. Everything past this point
  10. is handled by the sub protocol.
  11. ``` erlang
  12. init(Req, _Opts) ->
  13. {cowboy_websocket, Req, #state{}}.
  14. ```
  15. The return value may also have a `Timeout` value and/or the
  16. atom `hibernate`. These options are useful for long living
  17. connections. When they are not provided, the timeout value
  18. defaults to `infinity` and the hibernate value to `run`.
  19. The following snippet switches to the `my_protocol` sub
  20. protocol, sets the timeout value to 5 seconds and enables
  21. hibernation:
  22. ``` erlang
  23. init(Req, _Opts) ->
  24. {my_protocol, Req, #state{}, 5000, hibernate}.
  25. ```
  26. If a sub protocol does not make use of these options, it should
  27. crash if it receives anything other than the default values.
  28. :: Upgrade
  29. After the `init/2` function returns, Cowboy will then call the
  30. `upgrade/6` function. This is the only callback defined by the
  31. `cowboy_sub_protocol` behavior.
  32. The function is named `upgrade` because it mimics the mechanism
  33. of HTTP protocol upgrades. For some sub protocols, like Websocket,
  34. an actual upgrade is performed. For others, like REST, this is
  35. only an upgrade at Cowboy's level and the client has nothing to
  36. do about it.
  37. The upgrade callback receives the Req object, the middleware
  38. environment, the handler and its options, and the aforementioned
  39. timeout and hibernate values.
  40. ``` erlang
  41. upgrade(Req, Env, Handler, HandlerOpts, Timeout, Hibernate) ->
  42. %% Sub protocol code here.
  43. ```
  44. This callback is expected to behave like a middleware and to
  45. return an updated environment and Req object.
  46. Sub protocols are expected to call the `cowboy_handler:terminate/4`
  47. function when they terminate. This function will make sure that
  48. the optional `terminate/3` callback is called, if present.