Creating a module plug

A module plug has to export two functions: init and call. The init function is called at compile time, receives one argument, and its purpose is to prepare the options that will be passed to call. The call function is called at runtime and receives two arguments: the connection and the options returned by init. This function is where we'll transform the connection according to our needs. Having init allows you to prepare some of the work of your plug, which will be done during compilation. This way, call can be more performant, as its focus is solely on handling the request. Let's see an example:

$ cat my_module_plug.exdefmodule MyModulePlug do  import Plug.Conn   def init(options), do: options def call(conn, _options) ...

Get Mastering Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.