Cowboy provides two functions to access query parameters.
You can use the first to get the entire list of parameters.
QsVals = cowboy_req:parse_qs(Req),
{_, Lang} = lists:keyfind(<<"lang">>, 1, QsVals).
Cowboy will only parse the query string, and not do any
transformation. This function may therefore return duplicates,
or parameter names without an associated value. The order of
the list returned is undefined.
When a query string is key=1&key=2
, the list returned will
contain two parameters of name key
.
The same is true when trying to use the PHP-style suffix []
.
When a query string is key[]=1&key[]=2
, the list returned will
contain two parameters of name key[]
.
When a query string is simply key
, Cowboy will return the
list [{<<"key">>, true}]
, using true
to indicate that the
parameter key
was defined, but with no value.
The second function Cowboy provides allows you to match out
only the parameters you are interested in, and at the same
time do any post processing you require using constraints.
This function returns a map.
#{id := ID, lang := Lang} = cowboy_req:match_qs([id, lang], Req).
Constraints can be applied automatically. The following
snippet will crash when the id
parameter is not an integer,
or when the lang
parameter is empty. At the same time, the
value for id
will be converted to an integer term:
QsMap = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
A default value may also be provided. The default will be used
if the lang
key is not found. It will not be used if
the key is found but has an empty value.
#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
If no default is provided and the value is missing, the
query string is deemed invalid and the process will crash.
When the query string is key=1&key=2
, the value for key
will be the list [1, 2]
. Parameter names do not need to
include the PHP-style suffix. Constraints may be used to
ensure that only one value was passed through.