View Source Plug.Conn.Query (Plug v1.14.0)

Conveniences for decoding and encoding URL-encoded queries.

Plug allows developers to build query strings that map to Elixir structures in order to make manipulation of such structures easier on the server side. Here are some examples:

iex> decode("foo=bar")["foo"]
"bar"

If a value is given more than once, the last value takes precedence:

iex> decode("foo=bar&foo=baz")["foo"]
"baz"

Nested structures can be created via [key]:

iex> decode("foo[bar]=baz")["foo"]["bar"]
"baz"

Lists are created with []:

iex> decode("foo[]=bar&foo[]=baz")["foo"]
["bar", "baz"]

Keys without values are treated as empty strings, according to https://url.spec.whatwg.org/#application/x-www-form-urlencoded:

iex> decode("foo")["foo"]
""

Maps can be encoded:

iex> encode(%{foo: "bar", baz: "bat"})
"baz=bat&foo=bar"

Encoding keyword lists preserves the order of the fields:

iex> encode([foo: "bar", baz: "bat"])
"foo=bar&baz=bat"

When encoding keyword lists with duplicate keys, the key that comes first takes precedence:

iex> encode([foo: "bar", foo: "bat"])
"foo=bar"

Encoding named lists:

iex> encode(%{foo: ["bar", "baz"]})
"foo[]=bar&foo[]=baz"

Encoding nested structures:

iex> encode(%{foo: %{bar: "baz"}})
"foo[bar]=baz"

Link to this section Summary

Functions

Decodes the given tuple and stores it in the given accumulator.

Encodes the given map or list of tuples.

Link to this section Functions

Link to this function

decode(query, initial \\ %{}, invalid_exception \\ Plug.Conn.InvalidQueryError, validate_utf8 \\ true)

View Source
@spec decode(String.t(), map(), module(), boolean()) :: %{
  optional(String.t()) => term()
}

Decodes the given query.

The query is assumed to be encoded in the "x-www-form-urlencoded" format. The format is decoded at first. Then, if validate_utf8 is true, the decoded result is validated for proper UTF-8 encoding.

initial is the initial "accumulator" where decoded values will be added.

invalid_exception is the exception module for the exception to raise on errors with decoding.

@spec decode_pair(
  {String.t(), term()},
  acc
) :: acc
when acc: term()

Decodes the given tuple and stores it in the given accumulator.

It parses the key and stores the value into the current accumulator. The keys and values are not assumed to be encoded in "x-www-form-urlencoded".

Parameter lists are added to the accumulator in reverse order, so be sure to pass the parameters in reverse order.

Link to this function

encode(kv, encoder \\ &to_string/1)

View Source
@spec encode(Enumerable.t(), (term() -> binary())) :: binary()

Encodes the given map or list of tuples.