路由

时间:2017-03-29 16:53:59

标签: json go routing mux gorilla

我一直在尝试设置JSON配置文件来为我的应用程序设置动态路由。我的想法是,我将能够根据谁使用该服务来设置我自己的URL结构。我有一个接受JSON的结构,并且工作正常。我正在使用大猩猩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
}

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

  

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

我被告知使用类似的东西:

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

但我不知道如何做这项工作

2 个答案:

答案 0 :(得分:1)

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

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)
    }
}

答案 1 :(得分:1)

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

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