Plug v1.4.4 Plug.Conn View Source
The Plug connection.
This module defines a Plug.Conn
struct and the main functions
for working with Plug connections.
Note request headers are normalized to lowercase and response headers are expected to have lower-case keys.
Request fields
These fields contain request information:
host
- the requested host as a binary, example:"www.example.com"
method
- the request method as a binary, example:"GET"
path_info
- the path split into segments, example:["hello", "world"]
script_name
- the initial portion of the URL’s path that corresponds to the application routing, as segments, example: [“sub”,”app”].request_path
- the requested path, example:/trailing/and//double//slashes/
port
- the requested port as an integer, example:80
peer
- the actual TCP peer that connected, example:{{127, 0, 0, 1}, 12345}
. Often this is not the actual IP and port of the client, but rather of a load-balancer or request-router.remote_ip
- the IP of the client, example:{151, 236, 219, 228}
. This field is meant to be overwritten by plugs that understand e.g. theX-Forwarded-For
header or HAProxy’s PROXY protocol. It defaults to peer’s IP.req_headers
- the request headers as a list, example:[{"content-type", "text/plain"}]
. Note all headers will be downcased.scheme
- the request scheme as an atom, example::http
query_string
- the request query string as a binary, example:"foo=bar"
Fetchable fields
The request information in these fields is not populated until it is fetched
using the associated fetch_
function. For example, the cookies
field uses
fetch_cookies/2
.
If you access these fields before fetching them, they will be returned as
Plug.Conn.Unfetched
structs.
cookies
- the request cookies with the response cookiesbody_params
- the request body params, populated through aPlug.Parsers
parser.query_params
- the request query params, populated throughfetch_query_params/2
path_params
- the request path params, populated by routers such asPlug.Router
params
- the request params, the result of merging the:body_params
and:query_params
with:path_params
req_cookies
- the request cookies (without the response ones)
Response fields
These fields contain response information:
resp_body
- the response body, by default is an empty string. It is set to nil after the response is sent, except for test connections.resp_charset
- the response charset, defaults to “utf-8”resp_cookies
- the response cookies with their name and optionsresp_headers
- the response headers as a list of tuples, by defaultcache-control
is set to"max-age=0, private, must-revalidate"
. Note, response headers are expected to have lower-case keys.status
- the response status
Furthermore, the before_send
field stores callbacks that are invoked
before the connection is sent. Callbacks are invoked in the reverse order
they are registered (callbacks registered first are invoked last) in order
to reproduce a pipeline ordering.
Connection fields
assigns
- shared user data as a mapowner
- the Elixir process that owns the connectionhalted
- the boolean status on whether the pipeline was haltedsecret_key_base
- a secret key used to verify and encrypt cookies. the field must be set manually whenever one of those features are used. This data must be kept in the connection and never used directly, always usePlug.Crypto.KeyGenerator.generate/3
to derive keys from itstate
- the connection state
The connection state is used to track the connection lifecycle. It starts as
:unset
but is changed to :set
(via resp/3
) or :set_chunked
(used only for before_send
callbacks by send_chunked/2
) or :file
(when invoked via send_file/3
). Its final result is :sent
or
:chunked
depending on the response model.
Private fields
These fields are reserved for libraries/framework usage.
adapter
- holds the adapter information in a tupleprivate
- shared library data as a map
Protocols
Plug.Conn
implements both the Collectable and Inspect protocols
out of the box. The inspect protocol provides a nice representation
of the connection while the collectable protocol allows developers
to easily chunk data. For example:
# Send the chunked response headers
conn = send_chunked(conn, 200)
# Pipe the given list into a connection
# Each item is emitted as a chunk
Enum.into(~w(each chunk as a word), conn)
Custom status codes
Plug allows status codes to be overridden or added in order to allow new codes
not directly specified by Plug or its adapters. Adding or overriding a status
code is done through the Mix configuration of the :plug
application. For
example, to override the existing 404 reason phrase for the 404 status code
(“Not Found” by default) and add a new 451 status code, the following config
can be specified:
config :plug, :statuses, %{
404 => "Actually This Was Found",
451 => "Unavailable For Legal Reasons"
}
As this configuration is Plug specific, Plug will need to be recompiled for the changes to take place: this will not happen automatically as dependencies are not automatically recompiled when their configuration changes. To recompile Plug:
mix deps.clean --build plug
The atoms that can be used in place of the status code in many functions are inflected from the reason phrase of the status code. With the above configuration, the following will all work:
put_status(conn, :not_found) # 404
put_status(conn, :actually_this_was_found) # 404
put_status(conn, :unavailable_for_legal_reasons) # 451
Even though 404 has been overridden, the :not_found
atom can still be used
to set the status to 404 as well as the new atom :actually_this_was_found
inflected from the reason phrase “Actually This Was Found”.
Link to this section Summary
Functions
Assigns a value to a key in the connection
Starts a task to assign a value to a key in the connection
Awaits the completion of an async assign
Sends a chunk as part of a chunked response
Clears the entire session
Configures the session
Deletes a request header if present
Deletes a response cookie
Deletes a response header if present
Deletes the session for the given key
Fetches cookies from the request headers
Fetches query parameters from the query string
Fetches the session from the session store. Will also fetch cookies
Returns the values of the request header specified by key
Returns the values of the response header specified by key
Returns session value for the given key
Halts the Plug pipeline by preventing further plugs downstream from being
invoked. See the docs for Plug.Builder
for more information on halting a
plug pipeline
Merges a series of response headers into the connection
Assigns a new private key and value in the connection
Adds a new request header (key
) if not present, otherwise replaces the
previous value of that header with value
Sets the value of the "content-type"
response header taking into account the
charset
Puts a response cookie
Adds a new response header (key
) if not present, otherwise replaces the
previous value of that header with value
Puts the specified value
in the session for the given key
Stores the given status code in the connection
Reads the request body
Reads the body of a multipart request
Reads the headers of a multipart request
Registers a callback to be invoked before the response is sent
Sets the response to the given status
and body
Sends the response headers as a chunked response
Sends a file as the response body with the given status
and optionally starting at the given offset until the given length
Sends a response to the client
Sends a response with the given status and body
Updates a request header if present, otherwise it sets it to an initial value
Updates a response header if present, otherwise it sets it to an initial value
Link to this section Types
state() :: :unset | :set | :set_chunked | :set_file | :file | :chunked | :sent
t() :: %Plug.Conn{adapter: adapter(), assigns: assigns(), before_send: before_send(), body_params: params() | Plug.Conn.Unfetched.t(), cookies: cookies() | Plug.Conn.Unfetched.t(), halted: term(), host: host(), method: method(), owner: owner(), params: params() | Plug.Conn.Unfetched.t(), path_info: segments(), path_params: params(), peer: peer(), port: :inet.port_number(), private: assigns(), query_params: params() | Plug.Conn.Unfetched.t(), query_string: query_string(), remote_ip: :inet.ip_address(), req_cookies: cookies() | Plug.Conn.Unfetched.t(), req_headers: headers(), request_path: binary(), resp_body: body() | nil, resp_cookies: resp_cookies(), resp_headers: headers(), scheme: scheme(), script_name: segments(), secret_key_base: secret_key_base(), state: state(), status: int_status()}
Link to this section Functions
Assigns a value to a key in the connection
Examples
iex> conn.assigns[:hello]
nil
iex> conn = assign(conn, :hello, :world)
iex> conn.assigns[:hello]
:world
Starts a task to assign a value to a key in the connection.
await_assign/2
can be used to wait for the async task to complete and
retrieve the resulting value.
Behind the scenes, it uses Task.async/1
.
Examples
iex> conn.assigns[:hello]
nil
iex> conn = async_assign(conn, :hello, fn -> :world end)
iex> conn.assigns[:hello]
%Task{...}
Awaits the completion of an async assign.
Returns a connection with the value resulting from the async assignment placed
under key
in the :assigns
field.
Behind the scenes, it uses Task.await/2
.
Examples
iex> conn.assigns[:hello]
nil
iex> conn = async_assign(conn, :hello, fn -> :world end)
iex> conn = await_assign(conn, :hello) # blocks until `conn.assigns[:hello]` is available
iex> conn.assigns[:hello]
:world
Sends a chunk as part of a chunked response.
It expects a connection with state :chunked
as set by
send_chunked/2
. It returns {:ok, conn}
in case of success,
otherwise {:error, reason}
.
Clears the entire session.
This function removes every key from the session, clearing the session.
Note that, even if clear_session/1
is used, the session is still sent to the
client. If the session should be effectively dropped, configure_session/2
should be used with the :drop
option set to true
.
Configures the session.
Options
:renew
- generates a new session id for the cookie:drop
- drops the session, a session cookie will not be included in the response:ignore
- ignores all changes made to the session in this request cycle
Deletes a request header if present.
Raises a Plug.Conn.AlreadySentError
if the connection has already been
:sent
or :chunked
.
Deletes a response cookie.
Deleting a cookie requires the same options as to when the cookie was put.
Check put_resp_cookie/4
for more information.
Deletes a response header if present.
Raises a Plug.Conn.AlreadySentError
if the connection has already been
:sent
or :chunked
.
Deletes the session for the given key
.
The key can be a string or an atom, where atoms are automatically converted to strings.
Fetches cookies from the request headers.
Fetches query parameters from the query string.
This function does not fetch parameters from the body. To fetch
parameters from the body, use the Plug.Parsers
plug.
Options
:length
- the maximum query string length. Defaults to 1_000_000 bytes.
Fetches the session from the session store. Will also fetch cookies.
get_req_header(t(), binary()) :: [binary()]
Returns the values of the request header specified by key
.
get_resp_header(t(), binary()) :: [binary()]
Returns the values of the response header specified by key
.
Examples
iex> conn = %{conn | resp_headers: [{"content-type", "text/plain"}]}
iex> get_resp_header(conn, "content-type")
["text/plain"]
Returns session value for the given key
.
The key can be a string or an atom, where atoms are automatically converted to strings.
Halts the Plug pipeline by preventing further plugs downstream from being
invoked. See the docs for Plug.Builder
for more information on halting a
plug pipeline.
Merges a series of response headers into the connection.
Example
iex> conn = merge_resp_headers(conn, [{"content-type", "text/plain"}, {"X-1337", "5P34K"}])
Assigns a new private key and value in the connection.
This storage is meant to be used by libraries and frameworks to avoid writing
to the user storage (the :assigns
field). It is recommended for
libraries/frameworks to prefix the keys with the library name.
For example, if some plug needs to store a :hello
key, it
should do so as :plug_hello
:
iex> conn.private[:plug_hello]
nil
iex> conn = put_private(conn, :plug_hello, :world)
iex> conn.private[:plug_hello]
:world
Adds a new request header (key
) if not present, otherwise replaces the
previous value of that header with value
.
It is recommended for header keys to be in lower-case, to avoid sending
duplicate keys in a request. As a convenience, this is validated during
testing which raises a Plug.Conn.InvalidHeaderError
if the header key
is not lowercase.
Raises a Plug.Conn.AlreadySentError
if the connection has already been
:sent
or :chunked
.
Sets the value of the "content-type"
response header taking into account the
charset
.
Puts a response cookie.
The cookie value is not automatically escaped. Therefore, if you
want to store values with comma, quotes, etc, you need to explicitly
escape them or use a function such as Base.encode64
when writing
and Base.decode64
when reading the cookie.
Options
:domain
- the domain the cookie applies to:max_age
- the cookie max-age, in seconds. Providing a value for this option will set both the max-age and expires cookie attributes:path
- the path the cookie applies to:http_only
- when false, the cookie is accessible beyond http:secure
- if the cookie must be sent only over https. Defaults to true when the connection is https:extra
- string to append to cookie. Use this to take advantage of non-standard cookie attributes.
Adds a new response header (key
) if not present, otherwise replaces the
previous value of that header with value
.
It is recommended for header keys to be in lower-case, to avoid sending
duplicate keys in a request. As a convenience, this is validated during
testing which raises a Plug.Conn.InvalidHeaderError
if the header key
is not lowercase.
Raises a Plug.Conn.AlreadySentError
if the connection has already been
:sent
or :chunked
.
Raises a Plug.Conn.InvalidHeaderError
if the header value contains control
feed (\r) or newline (\n) characters.
Puts the specified value
in the session for the given key
.
The key can be a string or an atom, where atoms are
automatically converted to strings. Can only be invoked
on unsent conn
s. Will raise otherwise.
Stores the given status code in the connection.
The status code can be nil
, an integer or an atom. The list of allowed
atoms is available in Plug.Conn.Status
.
Raises a Plug.Conn.AlreadySentError
if the connection has already been
:sent
or :chunked
.
Reads the request body.
This function reads a chunk of the request body up to a given :length
. If
there is more data to be read, then {:more, partial_body, conn}
is
returned. Otherwise {:ok, body, conn}
is returned. In case of an error
reading the socket, {:error, reason}
is returned as per :gen_tcp.recv/2
.
In order to, for instance, support slower clients you can tune the
:read_length
and :read_timeout
options. These specify how much time should
be allowed to pass for each read from the underlying socket.
Because the request body can be of any size, reading the body will only
work once, as Plug will not cache the result of these operations. If you
need to access the body multiple times, it is your responsibility to store
it. Finally keep in mind some plugs like Plug.Parsers
may read the body,
so the body may be unavailable after being accessed by such plugs.
This function is able to handle both chunked and identity transfer-encoding by default.
Options
:length
- sets the maximum number of bytes to read from the body on every call, defaults to 8_000_000 bytes:read_length
- sets the amount of bytes to read at one time from the underlying socket to fill the chunk, defaults to 1_000_000 bytes:read_timeout
- sets the timeout for each socket read, defaults to 15_000ms
The values above are not meant to be exact. For example, setting the length to 8_000_000 may end up reading some hundred bytes more from the socket until we halt.
Examples
{:ok, body, conn} = Plug.Conn.read_body(conn, length: 1_000_000)
Reads the body of a multipart request.
Returns {:ok, body, conn}
if all body has been read,
{:more, binary, conn}
otherwise.
It accepts the same options as read_body/2
.
Reads the headers of a multipart request.
It returns {:ok, headers, conn}
with the headers or
{:done, conn}
if there are no more parts.
Once read_part_headers/2
is invoked, a developer may call
read_part_body/2
to read the body associated to the headers.
If read_part_headers/2
is called instead, the body is automatically
skipped until the next part headers.
Options
:length
- sets the maximum number of bytes to read from the body for each chunk, defaults to 64_000 bytes:read_length
- sets the amount of bytes to read at one time from the underlying socket to fill the chunk, defaults to 64_000 bytes:read_timeout
- sets the timeout for each socket read, defaults to 5_000ms
Registers a callback to be invoked before the response is sent.
Callbacks are invoked in the reverse order they are defined (callbacks defined first are invoked last).
Sets the response to the given status
and body
.
It sets the connection state to :set
(if not already :set
)
and raises Plug.Conn.AlreadySentError
if it was already :sent
.
Sends the response headers as a chunked response.
It expects a connection that has not been :sent
yet and sets its
state to :chunked
afterwards. Otherwise raises Plug.Conn.AlreadySentError
.
Sends a file as the response body with the given status
and optionally starting at the given offset until the given length.
If available, the file is sent directly over the socket using
the operating system sendfile
operation.
It expects a connection that has not been :sent
yet and sets its
state to :file
afterwards. Otherwise raises Plug.Conn.AlreadySentError
.
Examples
Plug.Conn.send_file(conn, 200, "README.md")
Sends a response to the client.
It expects the connection state to be :set
, otherwise raises an
ArgumentError
for :unset
connections or a Plug.Conn.AlreadySentError
for
already :sent
connections.
At the end sets the connection state to :sent
.
Sends a response with the given status and body.
See send_resp/1
for more information.
Updates a request header if present, otherwise it sets it to an initial value.
Raises a Plug.Conn.AlreadySentError
if the connection has already been
:sent
or :chunked
.
Updates a response header if present, otherwise it sets it to an initial value.
Raises a Plug.Conn.AlreadySentError
if the connection has already been
:sent
or :chunked
.