7

我正在使用牛仔(https://github.com/extend/cowboy)作为一项宁静的网络服务,我需要从“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.
4

2 回答 2

11

您应该使用该cowboy_http_req:qs_val/2功能,例如cowboy_http_req:qs_val(<<"a">>, Req),查看https://github.com/extend/cowboy/blob/master/examples/echo_get/src/toppage_handler.erl 的示例。

您还可以使用cowboy_http_req:qs_vals/1来检索所有查询字符串值的列表。

于 2012-07-24T09:26:10.030 回答
1

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.

于 2019-06-12T09:55:01.620 回答