【问题标题】:Golang JSON config for routes用于路由的 Golang JSON 配置
【发布时间】:2017-08-23 07:15:16
【问题描述】:

我一直在尝试设置一个 JSON 配置文件来为我的应用程序设置动态路由。这个想法是,我将能够根据谁在使用该服务来设置我自己的 URL 结构。我有一个接受 JSON 的结构并且工作正常。我正在使用 gorilla mux。

 type CustomRoute struct {
    Name string
    Method string
    Path string
    HandleFunc string
 }

JSON 与 struct 基本相同,并且可以正常运行。

我遇到的问题是获取 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
}

我总是收到以下错误(正如人们所期望的那样)

不能在赋值中使用 route.HandlerFunc (type string) 作为 http.Handler 类型: string 没有实现 http.Handler(缺少 ServeHTTP 方法)

有人告诉我使用类似的东西:

var functions = map[string]interface{}{
    "HandleFunc1": HandleFunc1,
}

但我不知道如何完成这项工作

【问题讨论】:

    标签: json go routing mux gorilla


    【解决方案1】:

    感谢RayenWindspear 我能够解决问题。这很简单(就像一切一样)。地图代码应如下所示:

    var functions = map[string]http.HandlerFunc{
        "HandleFunc1": HandleFunc1,
    }
    

    【讨论】:

      【解决方案2】:

      我正在为子域使用多路复用器,所以我的示例可能有点偏离。您被告知使用的地图是这样完成的:

      type Handlers map[string]http.HandlerFunc
      
      func (handlers Handlers) ServeHTTP(w http.ResponseWriter, r *http.Request) {
          path := r.URL.Path
          if handle := handlers[path]; handle != nil {
              handle.ServeHTTP(w, r)
          } else {
              http.Error(w, "Not found", 404)
          }
      }
      

      【讨论】:

      • 你帮我解决了,谢谢。我必须将我的地图更改为: var functions = map[string]http.HandlerFunc
      • 我认为有些事情会发生。就像我说的,我的特定于子域​​,因此是处理程序的映射。我实际上修改了函数中的第一行,从查找子域到获取路径,所以我的代码可能甚至不能按原样工作:O。我将对其进行编辑以使用 handleFuncs
      猜你喜欢
      • 2020-07-10
      • 2019-05-23
      • 2021-03-26
      • 2017-08-26
      • 2016-04-13
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多