大猩猩/mux中有任意深度的路径参数
我一直在努力制作一个API,该API通过从JSON文件
data.json
{
"data_1" : {
"depth2" : {
"depth3" : "Value of data 1"
}
},
"data_2" : {
"depth2" : {
"depth3" : "Value of data 2"
}
},
"data_3" : {
"depth2" : {
"depth3" : "Value of data 3"
}
}
}
中读取内容来发送JSON响应,我想建立一个动态的嵌套路由系统,如果客户端请求<,则为<代码>/api/data_1/depth2 我希望响应就像
{
"depth3" : "Value of data 1"
}
让我清楚地表明,请求路径可以无限期深... /api/data_1/depth2
或/api/data_1/depth2/depth3
,甚至/api/data_1/depth2/depth2/depth3/depth4
(取决于 data.json ),这意味着我不能像/api/{var_1}/{var_2}
那样走我的路径,因为它的深度已修复(即2层),所以
我需要帮助在我的代码
server.go
package main
import (
....
....
)
func main() {
// I'm using Gorilla/mux in my project
router := mux.NewRouter()
// Handle requests
router.HandleFunc("/api/what_should_I_write_here?", ApiHandler)
// Starting Server
log.Fatal(http.ListenAndServe(":8080", router))
}
中解决此问题,我已经有一个函数nestedlookup(data Map [string] interface {},key [] String)
,它将从嵌套返回数据MAP [String]接口{}
如果键是[“ data_1”,“ depth2” ...]
在apihandler
中。我只有在确定我的路由器
的正确路线时遇到问题
I've been working on making a API that would send a json response by reading contents from a json file
data.json
{
"data_1" : {
"depth2" : {
"depth3" : "Value of data 1"
}
},
"data_2" : {
"depth2" : {
"depth3" : "Value of data 2"
}
},
"data_3" : {
"depth2" : {
"depth3" : "Value of data 3"
}
}
}
I want to make a dynamic nested routing system where if the client requests for, say /api/data_1/depth2
I want the response to be like
{
"depth3" : "Value of data 1"
}
Let me make it clear that the request path can be indefinitely deep... like /api/data_1/depth2
or /api/data_1/depth2/depth3
or even /api/data_1/depth2/depth3/depth4
(depending upon data.json) which means I cant make my paths like /api/{var_1}/{var_2}
since its depth is fixed (ie 2 layers)
I need help in solving this in my code
server.go
package main
import (
....
....
)
func main() {
// I'm using Gorilla/mux in my project
router := mux.NewRouter()
// Handle requests
router.HandleFunc("/api/what_should_I_write_here?", ApiHandler)
// Starting Server
log.Fatal(http.ListenAndServe(":8080", router))
}
I already have a function NestedLookUp(data map[string]interface{}, key[]string)
that will return data from a nested map[string]interface{}
if the key is ["data_1", "depth2" ...]
called inside ApiHandler
. I only have problem figuring the correct route for my router
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只是为了详细说明我的评论,如果有一个不确定的深度,为什么不这样做?
Just to elaborate my comment, if there's an indefinite depth, why don't you get your depth path like so?