用大猩猩mux检索可选查询变量? [英] Retrieve optional query variables with gorilla mux?
问题描述
我正在编写一个可以采用POST或GET的处理程序.因此,我希望可以说:
I'm writing a handler that can take either POST or GET. As such, I want the option of being able to say:
http://host/query?parm1=value&parm2=value
我当时以为大猩猩多人种会给我:
I was assuming that Gorilla mux would then give me:
{
"parm1": "value",
"parm2": "value
}
但 mux.Vars(r)
为空.我知道使用 .Query("key","value"
将使参数成为必需参数,这不是我想要的.我缺少什么?
but mux.Vars(r)
is empty. I'm aware that using .Query("key", "value"
will make the parameters mandatory, which isn't what I want. What am I missing?
推荐答案
正如评论中所反映的,基本答案是那不是mux的目的". mux
非常擅长分解URL的 path 部分,并将这些组件转换为变量.举一个假设的例子,一个提供有关一个国家的信息的呼叫可能具有如下所示的规范:
As reflected in a comment, the basic answer is "that's not what mux is for". mux
is great at picking apart the path portion of a URL, and turning the components into variables. To give a hypothetical example, a call that gives information about a country might have a spec that looks like this:
country/{code}
并接受如下所示的呼叫:
and accept calls that look like this:
http://myhost/country/DE
您将获得 code
参数的值,如下所示:
You'd get the value of the code
parameter like this:
code := mux.Vars(r)["code"]
如果要传递查询变量,则不要使用mux进行.只需从请求中直接获取它们即可.因此,给出了替代查询语法:
If you want to pass query variables, you don't do that with mux. Just grab them straight from the request. So given the alternative query syntax:
http://myhost/country?code=DE
你会做的:
code := r.URL.Query().Get("code")
这篇关于用大猩猩mux检索可选查询变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!