'gorilla.mux'库中的'PathPrefix'是如何工作的?

7

我正在尝试使用Go语言的gorilla.mux库。我有以下配置,但我无法弄清如何访问HelloWorldXml方法的URL。

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/{name}.xml", HelloWorldXml).
           PathPrefix("/products/")
    router.HandleFunc("/hello/{name}", HelloWorld)
    http.Handle("/", router)
    http.ListenAndServe(":8787",nil)
}

应该使用什么URL呢?http://localhost:8787/products/MyName.xml返回404错误。

1个回答

15
 func main() {
    router := mux.NewRouter()
    router.HandleFunc("/{name}.xml", HelloWorldXml)
    subrouter := router.PathPrefix("/products/").Subrouter()
    //localhost/products/item.xml
    subrouter.HandleFunc("/{name}.xml", HelloWorldXmlHandler)
    router.HandleFunc("/hello/{name}", HelloWorld)
    http.Handle("/", router)
    http.ListenAndServe(":8787",nil)
}

1
所以,为了让路径前缀起作用,你需要创建一个子路由器?我猜我早就想到了,但从未尝试过。 - Vinnie
1
希望能从答案中获得更多的上下文/信息。 - Algebra8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接