json - Golang JSON 路由配置

标签 json go routes mux gorilla

我一直在尝试设置一个 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/

相关文章:

csv - 解析csv文件时出现奇怪的输出

通过充满多边形的空间路由的算法

php - 使Laravel 8 Slug变量不区分大小写

c# - 在数据成员 "__type"上反序列化 JSON 时出现问题

java - JSON到android/java中的多维数组

json - 为什么struct field的格式串总是小写

go - 我可以有像 os/arch 评论指令这样的自定义构建标志吗

docker - 如何从 Docker 容器内部访问在 WSL2 上运行的服务?

json - 为什么我应该更喜欢 HTTP REST 而不是 HTTP RPC JSON-Messaging 风格与 CQRS 结合使用?

javascript - 使用 javascript 将 JSON 数组转换为单独的变量