Plug.Builder

Parsed documentation:
View on GitHub
Conveniences for building plugs.

This module can be `use`-d into a module in order to build
a plug pipeline:

    defmodule MyApp do
      use Plug.Builder

      plug Plug.Logger
      plug :hello, upper: true

      # A function from another module can be plugged too, provided it's
      # imported into the current module first.
      import AnotherModule, only: [interesting_plug: 2]
      plug :interesting_plug

      def hello(conn, opts) do
        body = if opts[:upper], do: "WORLD", else: "world"
        send_resp(conn, 200, body)
      end
    end

Multiple plugs can be defined with the `plug/2` macro, forming a pipeline.
The plugs in the pipeline will be executed in the order they've been added
through the `plug/2` macro. In the example above, `Plug.Logger` will be
called first and then the `:hello` function plug will be called on the
resulting connection.

`Plug.Builder` also imports the `Plug.Conn` module, making functions like
`send_resp/3` available.

## Options

When used, the following options are accepted by `Plug.Builder`:

  * `:log_on_halt` - accepts the level to log whenever the request is halted

## Plug behaviour

Internally, `Plug.Builder` implements the `Plug` behaviour, which means both
the `init/1` and `call/2` functions are defined.

By implementing the Plug API, `Plug.Builder` guarantees this module is a plug
and can be handed to a web server or used as part of another pipeline.

## Overriding the default Plug API functions

Both the `init/1` and `call/2` functions defined by `Plug.Builder` can be
manually overridden. For example, the `init/1` function provided by
`Plug.Builder` returns the options that it receives as an argument, but its
behaviour can be customized:

    defmodule PlugWithCustomOptions do
      use Plug.Builder
      plug Plug.Logger

      def init(opts) do
        opts
      end
    end

The `call/2` function that `Plug.Builder` provides is used internally to
execute all the plugs listed using the `plug` macro, so overriding the
`call/2` function generally implies using `super` in order to still call the
plug chain:

    defmodule PlugWithCustomCall do
      use Plug.Builder
      plug Plug.Logger
      plug Plug.Head

      def call(conn, opts) do
        super(conn, opts) # calls Plug.Logger and Plug.Head
        assign(conn, :called_all_plugs, true)
      end
    end

## Halting a plug pipeline

A plug pipeline can be halted with `Plug.Conn.halt/1`. The builder will
prevent further plugs downstream from being invoked and return the current
connection. In the following example, the `Plug.Logger` plug never gets
called:

    defmodule PlugUsingHalt do
      use Plug.Builder

      plug :stopper
      plug Plug.Logger

      def stopper(conn, _opts) do
        halt(conn)
      end
    end
No suggestions.
Please help! Open an issue on GitHub if this assessment is incorrect.