Defining a plug
A plug takes two forms: a function plug and a module plug.
A function plug simply takes a connection with a set of options as a keyword list and returns a new connection. For example, the following Plug function just takes a connection, checks if it is authorized, and returns a halted connection if it is not:
import Plug.Conn
def authorization_plug(conn, opts) do
if is_authorized?(conn) do
conn
else
conn
|> put_resp_content_type("text/plain")
|> put_status(401)
|> halt()
end
end
Function plugs like this one are great for one-time use with not many use cases. However, if you want a plug to be called on multiple pipelines or to be part of a supervision tree, it’s better to use a module plug.
A Plug module can be used to transform a connection struct based on the given options and...