英文:
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
函数返回一个 map
,for 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论