duanru6816 2017-07-06 16:44
浏览 22
已采纳

如何从多路复用器中获取可用的路线?

I have a mux and 4 different routes.

a.Router = mux.NewRouter()

a.Router.HandleFunc("/1/query/{query}", a.sigQuery).Methods("GET")

a.Router.HandleFunc("/1/sis", a.rGet).Methods("GET")

a.Router.HandleFunc("/1/sigs", a.sigHandler).Methods("GET", "POST", "DELETE")

a.Router.HandleFunc("/1/nfeeds", a.nfeedGet).Methods("GET", "DELETE", "POST")

Is there a method where we can list the defined routes and get the methods defined on them. I was trying this way: routes := a.getRoutes() will return me a slice with all the routes, and methods := routes[1].Methods() will return the methods listed on that route. Is there a way we can achieve this?

  • 写回答

1条回答 默认 最新

  • dsfsd43523 2017-07-06 17:02
    关注

    Use the Walk method:

    router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
        tpl, err1 := route.GetPathTemplate()
        met, err2 := route.GetMethods()
        fmt.Println(tpl, err1, met, err2)
        return nil
    })
    

    Alternatively, you can just put all your routes into a slice of structs and just do

    for _, r := range routes {
        router.HandleFunc(r.tpl, r.func).Methods(r.methods...)
    }
    

    on the initialisation step.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?