2017-03-29 64 views
1

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

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(类型为字符串)类型http.Handler赋值: 字符串不执行http.Handler(缺少ServeHTTP法)

我被告知要使用这样的:

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

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

回答

1

感谢RayenWindspear我能解决这个问题。这非常简单(就像所有东西一样)。地图代码应该看起来像这样:

var functions = map[string]http.HandlerFunc{ 
    "HandleFunc1": HandleFunc1, 
} 
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) 
    } 
} 
+0

你让我在线上谢谢。我必须将我的地图更改为: var functions = map [string] http.HandlerFunc –

+0

我觉得有些东西是关闭的。就像我说的,我的是特定于子域​​的,因此是处理程序的地图。我实际上修改了函数中的第一行,从查找子域到获取路径,所以我的代码在这里可能不工作:O。我将编辑它以使用handleFuncs – RayfenWindspear