dongseshu0698 2017-03-29 16:53
浏览 70
已采纳

路由的Golang JSON配置

I have been trying to setup a JSON config file to setup dynamic routes for my application. The idea is that I will be able to setup my own URL structure depending on who is using the service. I have a struct that takes in JSON and that works fine. I am using gorilla mux.

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

The JSON is basically identical to the struct and it goes in fine.

The issue I have is getting the HandleFunc section.

Here is the code:

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
}

I always get the following error (as one would expect)

cannot use route.HandlerFunc (type string) as type http.Handler in assignment: string does not implement http.Handler (missing ServeHTTP method)

I was told to use something like:

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

But I have no idea how to make this work

  • 写回答

2条回答 默认 最新

  • duanchu7271 2017-03-29 17:21
    关注

    Thanks to RayenWindspear I was able to fix the problem. It was very simple (like everything). The map code should look like this:

    var functions = map[string]http.HandlerFunc{
        "HandleFunc1": HandleFunc1,
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services