我一直在尝试设置一个 JSON 配置文件来为我的应用程序设置动态路由。我的想法是,我将能够根据谁使用该服务来设置自己的 URL 结构。我有一个接受 JSON 的结构,并且运行良好。我正在使用 Gorilla mux。
type CustomRoute struct {
Name string
Method string
Path string
HandleFunc string
}
JSON 与结构基本相同,并且运行良好。
我遇到的问题是获取 HandleFunc 部分。
这是代码:
func NewRouter() *mux.Router {
routerInstance := mux.NewRouter().StrictSlash(true)
/*
All routes from the routing table
*/
// r = []CustomRoute with the JSON data
r := loadRoute()
for _, route := range r {
var handler http.Handler
handler = route.HandlerFunc
handler = core.Logger(handler, route.Name)
routerInstance.
Methods(route.Method).
Path(route.Path).
Name(route.Name).
Handler(handler)
}
return routerInstance
}
我总是收到以下错误(正如人们所期望的那样)
cannot use route.HandlerFunc (type string) as type http.Handler in assignment: string does not implement http.Handler (missing ServeHTTP method)
我被告知要使用类似的东西:
var functions = map[string]interface{}{
"HandleFunc1": HandleFunc1,
}
但我不知道如何进行这项工作
最佳答案
感谢RayenWindspear我能够解决这个问题。这非常简单(就像所有事情一样)。 map 代码应如下所示:
var functions = map[string]http.HandlerFunc{
"HandleFunc1": HandleFunc1,
}
关于json - Golang JSON 路由配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43099629/