How to get http params from Cowboy?

I use cowboy ( https://github.com/extend/cowboy ) for one quiet web service, I need to get the parameters from "http: // localhost: 8080 / = 1 & = 2 & = 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. 
+7
source share
2 answers

You should use the cowboy_http_req:qs_val/2 function, for example. cowboy_http_req:qs_val(<<"a">>, Req) , see 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 get a list of all the values โ€‹โ€‹of the query string.

+11
source

For those who have an upgrade to Cowboy 2, there are two ways to get request parameters.

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

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

Or specific using cowboy_req:match_qs/2 :

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

Read more in cowboy docs where these examples were found.

0
source

Source: https://habr.com/ru/post/921181/


All Articles