How to get http params from Cowboy?
Asked Answered
S

2

8

I am using cowboy( https://github.com/extend/cowboy) for one restful web service, I need to get the params from "http://localhost:8080/?a=1&b=2&c=32"

init({tcp, http}, Req, Opts) ->
    log4erl:debug("~p~n", [Opts]),
    {ok, Req, undefined_state}.

handle(Req, State) ->
    {ok, Req2} = cowboy_http_req:reply(200, [], <<"Hello World!">>, Req),
    io:format("How to get the params from Req ? "),
    {ok, Req2, State}.

terminate(Req, State) ->
    log4erl:debug("~p~p~n", [Req, State]),
    ok.
Sanyu answered 24/7, 2012 at 8:48 Comment(0)
B
11

You should use the cowboy_http_req:qs_val/2 function, e.g. cowboy_http_req:qs_val(<<"a">>, Req), look at https://github.com/extend/cowboy/blob/master/examples/echo_get/src/toppage_handler.erl for an example.

You can also use cowboy_http_req:qs_vals/1 to retrieve a list of all query string values.

Bannister answered 24/7, 2012 at 9:26 Comment(0)
I
3

For anyone who have upgrade to Cowboy 2, there are two ways of getting the query params.

You can get them all by using cowboy_req:parse_qs/1:

QsVals = cowboy_req:parse_qs(Req),
{_, Lang} = lists:keyfind(<<"lang">>, 1, QsVals).

Or specific ones by using cowboy_req:match_qs/2:

#{id := ID, lang := Lang} = cowboy_req:match_qs([id, lang], Req).

Read more in the cowboy docs where these examples where found.

Inerrable answered 12/6, 2019 at 9:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.