猿问

获取 Golang HTTP 或 Gorilla 包中的路由和参数列表

当我像这样编写一个简单的 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)

}

如何找到我在 Web 应用程序中定义的路线和参数列表?例如,在本例中查找“/about”。


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


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

    res.Write([]byte("Regexp works :)"))

})


潇湘沐
浏览 451回答 3
3回答

梵蒂冈之花

您可以使用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)}功能 gorillaWalkFn:func gorillaWalkFn(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {    path, err := route.GetPathTemplate()    return nil}该path变量包含您的模板:“/路径/{param1}”但您应该手动提取参数。

尚方宝剑之说

您可以看到 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)

aluckdog

我想一个改进的答案。它提供了缺失的一段代码来从路由路径模板字符串中提取参数。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}
随时随地看视频慕课网APP

相关分类

Go
我要回答