The Cowboy routing guide says that each path is structured as a tuple that includes "options that will be given to it [the request handler] on initialization". But it doesn't explain the purpose of the options, and I'm not sure how to use them given that the Req object passed to the handler contains information on the path and its bindings.
So if routing options don't contain any unique path information, what use cases do they have?
Options are passed to handlers init/3
method. In the handlers guide there is example of using options for translation. You can have multiple paths pointing to the same handler, with different option:
{"/pl", toppage_handler, [{lang, fr}]}
{"/en", toppage_handler, [{lang, en}]}
In handler, you could have something like this:
-record(state, {
lang :: en | fr
%% More fields here.
}).
init(_Type, Req, Opts) ->
{_, Lang} = lists:keyfind(lang, 1, Opts),
{ok, Req, #state{lang=Lang}}.
handle(Req, State#state{lang = Lang}) ->
{ok, Req2} = cowboy_req:reply(200, [
{<<"content-type">>, <<"text/plain">>}
], translate_text(<<"Hello World!">>, Lang), Req),
{ok, Req2, State}.
Another example is taking the language from hostname. You could for example detect language based on host, which got the request.
[{'fr.example.org', [
{"/", toppage_handler, [{lang, fr}]
]},
{'en.example.org', [
{"/", toppage_handler, [{lang, en}]
].
You could achieve the same, using PathMatch
and HostMatch
and language value binding would be in Req
, but options are more general. Routing options are used to create additional information and pass it to handler.