【问题标题】:Get a list of routes and params in Golang HTTP or Gorilla package获取 Golang HTTP 或 Gorilla 包中的路由和参数列表
【发布时间】:2019-06-25 20:25:01
【问题描述】:

当我像这样编写一个简单的 Web 应用程序时:

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/about", handler)
    http.ListenAndServe(":8080", nil)
}

如何找到我在网络应用程序中定义的路线和参数列表? 例如在这个例子中找到“/about”。

编辑 1: 如何获得这一参数和路线?

gorilla.HandleFunc(`/check/{id:[0-9]+}`, func(res http.ResponseWriter, req *http.Request) {
    res.Write([]byte("Regexp works :)"))
})

【问题讨论】:

  • 您想通过找到这个来解决什么要求?
  • 使用 gorilla/mux:您可以使用 router.Walk 来遍历路由器,然后调用 route.GetPathTemplate 来获取该路由的模式。

标签: web-services go gorilla


【解决方案1】:

您可以使用http.DefaultServeMux(输入ServeMux)并检查它。使用reflect 包,您可以ValueOf 默认多路复用器并提取m 属性,这是您的路线图。

v := reflect.ValueOf(http.DefaultServeMux).Elem()
fmt.Printf("routes: %v\n", v.FieldByName("m"))

更新

如果您使用net/http,那么您应该在您自己实际完成任何请求之前实现提取参数;否则你可以通过r.URL.Query()访问参数

如果你使用gorilla/mux而不是elithrar提到你应该使用Walk

主函数

r := mux.NewRouter()
r.HandleFunc("/path/{param1}", handler)

err := r.Walk(gorillaWalkFn)
if err != nil {
    log.Fatal(err)
}

func gorillaWalkFn

func gorillaWalkFn(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
    path, err := route.GetPathTemplate()
    return nil
}

path 变量包含您的模板:

"/path/{param1}"

但您应该手动提取参数。

【讨论】:

  • 谢谢,但它只返回路线列表我如何返回 /:id 之类的参数?请再次检查我的问题,我编辑了它
  • 我已经更新了答案,请检查它是否有帮助
【解决方案2】:

您可以看到 HTTP 包中的路由列表。

http.HandleFunc("/favicon.ico", func(res http.ResponseWriter, req *http.Request) {
    http.ServeFile(res, req, "favicon.ico")
})
http.HandleFunc(`/check`, func(res http.ResponseWriter, req *http.Request) {
    res.Write([]byte("Regexp works :)"))
})

httpMux := reflect.ValueOf(http.DefaultServeMux).Elem()
finList := httpMux.FieldByIndex([]int{1})
fmt.Println(finList)

【讨论】:

    【解决方案3】:

    我猜是一个改进的答案。

    它提供了从路由路径模板字符串中提取参数的缺失代码。

    
    var pathTemplateRegex = regexp.MustCompile(`\{(\\?[^}])+\}`)
    
    func getRouteParams(router *mux.Router, route string) []string {
        r := router.Get(route)
        if r == nil {
            return nil
        }
        t, _ := r.GetPathTemplate()
        params := pathTemplateRegex.FindAllString(t, -1)
        for i, p := range params {
            p = strings.TrimPrefix(p, "{")
            p = strings.TrimSuffix(p, "}")
            if strings.ContainsAny(p, ":") {
                p = strings.Split(p, ":")[0]
            }
            params[i] = p
        }
        return params
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-09
      • 2014-09-08
      • 2023-03-30
      • 1970-01-01
      • 2017-11-07
      • 2014-10-09
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多