W3cubDocs

/Phoenix

Plug.Conn

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 lowercase 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
  • 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. the X-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 cookies
  • body_params - the request body params, populated through a Plug.Parsers parser.
  • query_params - the request query params, populated through fetch_query_params/2
  • path_params - the request path params, populated by routers such as Plug.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 options
  • resp_headers - the response headers as a list of tuples, by default cache-control is set to "max-age=0, private, must-revalidate". Note, response headers are expected to have lowercase 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 map
  • owner - the Elixir process that owns the connection
  • halted - the boolean status on whether the pipeline was halted
  • secret_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 use Plug.Crypto.KeyGenerator.generate/3 to derive keys from it
  • state - 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, :file or :chunked depending on the response model.

Private fields

These fields are reserved for libraries/framework usage.

  • adapter - holds the adapter information in a tuple
  • private - shared library data as a map

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 998 status code, the following config can be specified:

config :plug, :statuses, %{
  404 => "Actually This Was Found",
  998 => "Not An RFC Status Code"
}

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, :not_an_rfc_status_code)        # 998

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”.

Summary

Types

adapter()
assigns()
before_send()
body()
cookies()
halted()
headers()
host()
int_status()
method()
owner()
param()
params()
port_number()
query_string()
resp_cookies()
scheme()
secret_key_base()
segments()
state()
status()
t()

Functions

assign(conn, key, value)

Assigns a value to a key in the connection

chunk(conn, chunk)

Sends a chunk as part of a chunked response

clear_session(conn)

Clears the entire session

configure_session(conn, opts)

Configures the session

delete_req_header(conn, key)

Deletes a request header if present

delete_resp_cookie(conn, key, opts \\ [])

Deletes a response cookie

delete_resp_header(conn, key)

Deletes a response header if present

delete_session(conn, key)

Deletes the session for the given key

fetch_cookies(conn, opts \\ [])

Fetches cookies from the request headers

fetch_query_params(conn, opts \\ [])

Fetches query parameters from the query string

fetch_session(conn, opts \\ [])

Fetches the session from the session store. Will also fetch cookies

get_http_protocol(conn)

Returns the HTTP protocol and version

get_peer_data(conn)

Returns the request peer data if one is present

get_req_header(conn, key)

Returns the values of the request header specified by key

get_resp_header(conn, key)

Returns the values of the response header specified by key

get_session(conn, key)

Returns session value for the given key. If key is not set, nil is returned

halt(conn)

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

inform!(conn, status, headers \\ [])

Sends an information response to a client but raises if the adapter does not support inform

inform(conn, status, headers \\ [])

Sends and informational response to the client

merge_assigns(conn, keyword)

Assigns multiple values to keys in the connection

merge_private(conn, keyword)

Assigns multiple private keys and values in the connection

merge_resp_headers(conn, headers)

Merges a series of response headers into the connection

prepend_resp_headers(conn, headers)

Prepends the list of headers to the connection response headers

push!(conn, path, headers \\ [])

Pushes a resource to the client but raises if the adapter does not support server push

push(conn, path, headers \\ [])

Pushes a resource to the client

put_private(conn, key, value)

Assigns a new private key and value in the connection

put_req_header(conn, key, value)

Adds a new request header (key) if not present, otherwise replaces the previous value of that header with value

put_resp_content_type(conn, content_type, charset \\ "utf-8")

Sets the value of the "content-type" response header taking into account the charset

put_resp_cookie(conn, key, value, opts \\ [])

Puts a response cookie in the connection

put_resp_header(conn, key, value)

Adds a new response header (key) if not present, otherwise replaces the previous value of that header with value

put_session(conn, key, value)

Puts the specified value in the session for the given key

put_status(conn, status)

Stores the given status code in the connection

read_body(conn, opts \\ [])

Reads the request body

read_part_body(conn, opts)

Reads the body of a multipart request

read_part_headers(conn, opts \\ [])

Reads the headers of a multipart request

register_before_send(conn, callback)

Registers a callback to be invoked before the response is sent

request_url(conn)

Returns the full request URL

resp(conn, status, body)

Sets the response to the given status and body

send_chunked(conn, status)

Sends the response headers as a chunked response

send_file(conn, status, file, offset \\ 0, length \\ :all)

Sends a file as the response body with the given status and optionally starting at the given offset until the given length

send_resp(conn)

Sends a response to the client

send_resp(conn, status, body)

Sends a response with the given status and body

update_req_header(conn, key, initial, fun)

Updates a request header if present, otherwise it sets it to an initial value

update_resp_header(conn, key, initial, fun)

Updates a response header if present, otherwise it sets it to an initial value

Types

adapter()

adapter() :: {module(), term()}

assigns()

assigns() :: %{optional(atom()) => any()}

before_send()

before_send() :: [(t() -> t())]

body()

body() :: iodata()

cookies()

cookies() :: %{optional(binary()) => binary()}

halted()

halted() :: boolean()

headers()

headers() :: [{binary(), binary()}]

host()

host() :: binary()

int_status()

int_status() :: non_neg_integer() | nil

method()

method() :: binary()

owner()

owner() :: pid()

param()

param() :: binary() | %{optional(binary()) => param()} | [param()]

params()

params() :: %{optional(binary()) => param()}

port_number()

port_number() :: :inet.port_number()

query_string()

query_string() :: String.t()

resp_cookies()

resp_cookies() :: %{optional(binary()) => %{}}

scheme()

scheme() :: :http | :https

secret_key_base()

secret_key_base() :: binary() | nil

segments()

segments() :: [binary()]

state()

state() :: :unset | :set | :set_chunked | :set_file | :file | :chunked | :sent

status()

status() :: atom() | int_status()

t()

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(),
  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()
}

Functions

assign(conn, key, value)

assign(t(), atom(), term()) :: t()

Assigns a value to a key in the connection.

The “assigns” storage is meant to be used to store values in the connection so that other plugs in your plug pipeline can access them. The assigns storage is a map.

Examples

iex> conn.assigns[:hello]
nil
iex> conn = assign(conn, :hello, :world)
iex> conn.assigns[:hello]
:world

chunk(conn, chunk)

chunk(t(), body()) :: {:ok, t()} | {:error, term()} | no_return()

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}.

To stream data use Enum.reduce_while/3 instead of Enum.into/2. Enum.reduce_while/3 allows aborting the execution if chunk/2 fails to deliver the chunk of data.

Example

Enum.reduce_while(~w(each chunk as a word), conn, fn (chunk, conn) ->
  case Plug.Conn.chunk(conn, chunk) do
    {:ok, conn} ->
      {:cont, conn}
    {:error, :closed} ->
      {:halt, conn}
  end
end)

clear_session(conn)

clear_session(t()) :: t()

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.

configure_session(conn, opts)

configure_session(t(), Keyword.t()) :: t()

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

delete_req_header(conn, key)

delete_req_header(t(), binary()) :: t()

Deletes a request header if present.

Raises a Plug.Conn.AlreadySentError if the connection has already been :sent or :chunked.

Examples

Plug.Conn.delete_req_header(conn, "content-type")

delete_resp_cookie(conn, key, opts \\ [])

delete_resp_cookie(t(), binary(), Keyword.t()) :: t()

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.

delete_resp_header(conn, key)

delete_resp_header(t(), binary()) :: t()

Deletes a response header if present.

Raises a Plug.Conn.AlreadySentError if the connection has already been :sent or :chunked.

Examples

Plug.Conn.delete_resp_header(conn, "content-type")

delete_session(conn, key)

delete_session(t(), String.t() | atom()) :: t()

Deletes the session for the given key.

The key can be a string or an atom, where atoms are automatically converted to strings.

fetch_cookies(conn, opts \\ [])

fetch_cookies(t(), Keyword.t()) :: t()

Fetches cookies from the request headers.

fetch_query_params(conn, opts \\ [])

fetch_query_params(t(), Keyword.t()) :: t()

Fetches query parameters from the query string.

Params are decoded as "x-www-form-urlencoded" in which key/value pairs are separated by & and keys are separated from values by =.

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.

fetch_session(conn, opts \\ [])

fetch_session(t(), Keyword.t()) :: t()

Fetches the session from the session store. Will also fetch cookies.

get_http_protocol(conn)

get_http_protocol(t()) :: Plug.Conn.Adapter.http_protocol()

Returns the HTTP protocol and version.

Examples

iex> get_http_protocol(conn)
:"HTTP/1.1"

get_peer_data(conn)

get_peer_data(t()) :: Plug.Conn.Adapter.peer_data()

Returns the request peer data if one is present.

get_req_header(conn, key)

get_req_header(t(), binary()) :: [binary()]

Returns the values of the request header specified by key.

Examples

iex> get_req_header(conn, "accept")
["application/json"]

get_resp_header(conn, 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"]

get_session(conn, key)

get_session(t(), String.t() | atom()) :: any()

Returns session value for the given key. If key is not set, nil is returned.

The key can be a string or an atom, where atoms are automatically converted to strings.

halt(conn)

halt(t()) :: t()

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.

inform!(conn, status, headers \\ [])

inform!(t(), status(), Keyword.t()) :: t()

Sends an information response to a client but raises if the adapter does not support inform.

See inform/1 for more information.

inform(conn, status, headers \\ [])

inform(t(), status(), Keyword.t()) :: t()

Sends and informational response to the client.

An informational response, such as an early hint, must happen prior to a response being sent. If an informational request is attempted after a response is sent then a Plug.Conn.AlreadySentError will be raised. Only status codes from 100-199 are valid.

To use inform for early hints send one or more informs with a status of 103.

If the adapter does not support informational responses then this is a noop.

Most HTTP/1.1 clients do not properly support informational responses but some proxies require it to support server push for HTTP/2. You can call get_http_protocol/1 to retrieve the protocol and version.

merge_assigns(conn, keyword)

merge_assigns(t(), Keyword.t()) :: t()

Assigns multiple values to keys in the connection.

Equivalent to multiple calls to assign/3.

Examples

iex> conn.assigns[:hello]
nil
iex> conn = merge_assigns(conn, hello: :world)
iex> conn.assigns[:hello]
:world

merge_private(conn, keyword)

merge_private(t(), Keyword.t()) :: t()

Assigns multiple private keys and values in the connection.

Equivalent to multiple put_private/3 calls.

Examples

iex> conn.private[:my_plug_hello]
nil
iex> conn = merge_private(conn, my_plug_hello: :world)
iex> conn.private[:my_plug_hello]
:world

merge_resp_headers(conn, headers)

merge_resp_headers(t(), Enum.t()) :: t()

Merges a series of response headers into the connection.

Example

Plug.Conn.merge_resp_headers(conn, [{"content-type", "text/plain"}, {"X-1337", "5P34K"}])

prepend_resp_headers(conn, headers)

prepend_resp_headers(t(), headers()) :: t()

Prepends the list of headers to the connection response headers.

Similar to put_resp_header this functions adds a new response header (key) but rather then replacing the existing one it prepends another header with the same key.

It is recommended for header keys to be in lowercase, to avoid sending duplicate keys in a request. As a convenience, when using the Plug.Adapters.Conn.Test adapter, any headers that aren’t lowercase will raise a Plug.Conn.InvalidHeaderError.

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.

Examples

Plug.Conn.prepend_resp_headers(conn, "content-type", "application/json")

push!(conn, path, headers \\ [])

push!(t(), String.t(), Keyword.t()) :: t()

Pushes a resource to the client but raises if the adapter does not support server push.

push(conn, path, headers \\ [])

push(t(), String.t(), Keyword.t()) :: t()

Pushes a resource to the client.

Server pushes must happen prior to a response being sent. If a server push is attempted after a response is sent then a Plug.Conn.AlreadySentError will be raised.

If the adapter does not support server push then this is a noop.

Note that certain browsers (such as Google Chrome) will not accept a pushed resource if your certificate is not trusted. In the case of Chrome this means a valid cert with a SAN. See https://www.chromestatus.com/feature/4981025180483584

put_private(conn, key, value)

put_private(t(), atom(), term()) :: t()

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 a plug called my_plug needs to store a :hello key, it would store it as :my_plug_hello:

iex> conn.private[:my_plug_hello]
nil
iex> conn = put_private(conn, :my_plug_hello, :world)
iex> conn.private[:my_plug_hello]
:world

put_req_header(conn, key, value)

put_req_header(t(), binary(), binary()) :: t()

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 lowercase, to avoid sending duplicate keys in a request. As a convenience, when using the Plug.Adapters.Conn.Test adapter, any headers that aren’t lowercase will raise a Plug.Conn.InvalidHeaderError.

Raises a Plug.Conn.AlreadySentError if the connection has already been :sent or :chunked.

Examples

Plug.Conn.put_req_header(conn, "accept", "application/json")

put_resp_content_type(conn, content_type, charset \\ "utf-8")

put_resp_content_type(t(), binary(), binary() | nil) :: t()

Sets the value of the "content-type" response header taking into account the charset.

If charset is nil, the value of the "content-type" response header won’t specify a charset.

Examples

iex> conn = put_resp_content_type(conn, "application/json")
iex> get_resp_header(conn, "content-type")
["application/json; charset=utf-8"]

put_resp_cookie(conn, key, value, opts \\ [])

put_resp_cookie(t(), binary(), binary(), Keyword.t()) :: t()

Puts a response cookie in the connection.

The cookie value is not automatically escaped. Therefore, if you want to store values with comma, quotes, and so on, you need to explicitly escape them or use a function such as Base.encode64(value, padding: false) when writing and Base.decode64(encoded, padding: false) when reading the cookie. Padding needs to be disabled since = is not a valid character in cookie values.

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.

put_resp_header(conn, key, value)

put_resp_header(t(), binary(), binary()) :: t()

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 lowercase, to avoid sending duplicate keys in a request. As a convenience, when using the Plug.Adapters.Conn.Test adapter, any headers that aren’t lowercase will raise a Plug.Conn.InvalidHeaderError.

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.

Examples

Plug.Conn.put_resp_header(conn, "content-type", "application/json")

put_session(conn, key, value)

put_session(t(), String.t() | atom(), any()) :: t()

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 conns. Will raise otherwise.

put_status(conn, status)

put_status(t(), status()) :: t()

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.

Examples

Plug.Conn.put_status(conn, :not_found)
Plug.Conn.put_status(conn, 200)

read_body(conn, opts \\ [])

read_body(t(), Keyword.t()) ::
  {:ok, binary(), t()} | {:more, binary(), t()} | {:error, term()}

Reads the request body.

This function reads a chunk of the request body up to a given length (specified by the :length option). 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.

Like all functions in this module, the conn returned by read_body must be passed to the next stage of your pipeline and should not be ignored.

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_000 milliseconds

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)

read_part_body(conn, opts)

read_part_body(t(), Keyword.t()) ::
  {:ok, binary(), t()} | {:more, binary(), t()} | {:done, t()}

Reads the body of a multipart request.

Returns {:ok, body, conn} if all body has been read, {:more, binary, conn} otherwise, and {:done, conn} if there is no more body.

It accepts the same options as read_body/2.

read_part_headers(conn, opts \\ [])

read_part_headers(t(), Keyword.t()) ::
  {:ok, headers(), t()} | {:done, t()}

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, you 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_000 milliseconds

register_before_send(conn, callback)

register_before_send(t(), (t() -> t())) :: t()

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).

Examples

To log the status of requests being sent:

require Logger

Plug.Conn.register_before_send(conn, fn conn ->
  Logger.info("Sent a #{conn.status} response")
  conn
end)

request_url(conn)

Returns the full request URL.

resp(conn, status, body)

resp(t(), status(), body()) :: t()

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.

If you also want to send the response, use send_resp/1 after this or use send_resp/3.

The status can be an integer, an atom, or nil. See Plug.Conn.Status for more information.

Examples

Plug.Conn.resp(conn, 404, "Not found")

send_chunked(conn, status)

send_chunked(t(), status()) :: t() | no_return()

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. After send_chunked/2 is called, chunks can be sent to the client via the chunk/2 function.

HTTP/2 does not support chunking and will instead stream the response without a transfer encoding. When using HTTP/1.1, the Cowboy adapter will stream the response instead of emitting chunks if the content-length header has been set before calling send_chunked/2.

send_file(conn, status, file, offset \\ 0, length \\ :all)

send_file(
  t(),
  status(),
  filename :: binary(),
  offset :: integer(),
  length :: integer() | :all
) :: t() | no_return()

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")

send_resp(conn)

send_resp(t()) :: t() | no_return()

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.

Note that this function does not halt the connection, so if subsequent plugs try to send another response, it will error out. Use halt/1 after this function if you want to halt the plug pipeline.

Examples

conn
|> Plug.Conn.resp(404, "Not found")
|> Plug.Conn.send_resp()

send_resp(conn, status, body)

send_resp(t(), status(), body()) :: t() | no_return()

Sends a response with the given status and body.

This is equivalent to setting the status and the body and then calling send_resp/1.

Note that this function does not halt the connection, so if subsequent plugs try to send another response, it will error out. Use halt/1 after this function if you want to halt the plug pipeline.

Examples

Plug.Conn.send_resp(conn, 404, "Not found")

update_req_header(conn, key, initial, fun)

update_req_header(t(), binary(), binary(), (binary() -> binary())) :: t()

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.

Only the first value of the header key is updated if present.

Examples

Plug.Conn.update_req_header(
  conn,
  "accept",
  "application/json; charset=utf-8",
  &(&1 <> "; charset=utf-8")
)

update_resp_header(conn, key, initial, fun)

update_resp_header(t(), binary(), binary(), (binary() -> binary())) :: t()

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.

Only the first value of the header key is updated if present.

Examples

Plug.Conn.update_resp_header(
  conn,
  "content-type",
  "application/json; charset=utf-8",
  &(&1 <> "; charset=utf-8")
)

© 2013 Plataformatec
Licensed under the Apache License, Version 2.0.
https://hexdocs.pm/plug/Plug.Conn.html