如何列出 Gorilla Mux 中的所有变量?

huangapple go评论93阅读模式
英文:

How to list all variables in Gorilla Mux?

问题

当你在Golang中创建一个funcHandler并使用Gorilla Mux时,我知道你可以通过调用Mux.Vars来访问特定的输入变量。然而,我不确定当你的数据以JSON格式存储时,这是如何工作的,部分原因是我不确定Mux.Vars()是如何工作的。所以,我想知道如何列出在进入funcHandler时由Mux.Vars()存储的所有变量,并且如何解析存储在URL中的JSON(例如,/data?name="bill"&value="red",我想要找到name和value键的值)。

英文:

When you create a funcHandler in Golang and use Gorilla Mux, I know that you can access a specific input variable by calling Mux.Vars. However, I'm not sure how that works when you have data stored in JSON format, and part of that is because I'm not sure how Mux.Vars() works. So, I'd like to know how to list all variables stored by Mux.Vars() when you enter a funcHandler and how to parse JSON stored in a URL (ie, /data?name="bill"&value="red", where I would want to find the value of the name and value keys).

答案1

得分: 0

列出所有 Gorilla Mux 的代码:

for k, v := range mux.Vars(request) {
    log.Printf("key=%v, value=%v", k, v)
}

Vars 函数返回一个 mapfor range 循环可以帮助你读取所有的项,就像我给你展示的那样。
但是我觉得你的问题有点不同,如果你想读取发送请求时的 JSON 数据或其他类型的数据,你需要读取请求的 Body(req.Body)。请注意,请求的 Body 是一个 Reader 接口而不是字符串。如果你期望输入是 JSON 格式的示例,请参考以下链接:
https://stackoverflow.com/questions/15672556/handling-json-post-request-in-go

英文:

For list all Gorilla Mux:

for k, v := range mux.Vars(request) {
    log.Printf("key=%v, value=%v", k, v)
}

The Vars function return a map, for range loop help you read all the items like I show you.
But I think your question is a bit different, if you want to read the JSON data or other kid of data that send with the request, you need to read the request Body (req.Body). Note that request Body is a Reader interface not a string. An example if you expect the input in JSON format:
https://stackoverflow.com/questions/15672556/handling-json-post-request-in-go

huangapple
  • 本文由 发表于 2015年10月20日 05:45:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/33224464.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定