2016-05-14 82 views
2

當我寫這樣一個簡單的Web應用程序:獲取途徑,而params列表中Golang HTTP或大猩猩包

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應用程序定義的路由,而params名單? 例如在本例中找到「/ about」。

編輯1: 如何得到這一個參數和路線?

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

需要什麼,你試圖解決這個問題? – Venkat

+0

與大猩猩/多路複用器:你可以使用['router.Walk'](https://godoc.org/github.com/gorilla/mux#Router.Walk)來走路由器,然後調用['route.GetPathTemplate '](https://godoc.org/github.com/gorilla/mux#Route.GetPathTemplate)獲取該路線的模式。 – elithrar

回答

4

你可以使用http.DefaultServeMux(類型ServeMux),並檢查它。用reflect包你可以ValueOf默認多路複用器和提取m屬性這是你的路線圖。

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

UPD

如果你使用 net/http比你應該實現提取PARAMS之前的任何請求,實際上是由自己完成

;否則,你有r.URL.Query()

訪問PARAMS如果使用gorilla/mux不是elithrar提到你應該使用Walk

FUNC主要

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變量包含您的模板:

「/路徑/ {參數1}」

,但你應該手動提取PARAMS。

+1

謝謝,但它只是返回一個路由列表,我怎麼能返回params像/:id?請再次檢查我的問題我編輯了它 –

+0

我已經更新了答案,請檢查它是否有幫助 – hsrv

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)