How does 'PathPrefix' work in 'gorilla.mux' library for Go?

huangapple go评论71阅读模式
英文:

How does 'PathPrefix' work in 'gorilla.mux' library for Go?

问题

你好!根据你提供的代码,正确的URL应该是http://localhost:8787/products/MyName.xml。但是,你提到这个URL返回404错误。可能有几个原因导致这个问题:

  1. 请确保你的服务器正在监听端口8787,并且没有其他进程占用了该端口。
  2. 确保你的代码中没有其他地方对该URL进行了处理,可能会导致路由冲突。
  3. 检查HelloWorldXml方法是否正确实现,并且没有其他错误导致返回404。

请仔细检查以上几点,如果问题仍然存在,请提供更多的代码和错误信息,以便我能够更好地帮助你解决问题。

英文:

I'm playing around with the gorilla.mux library for Go. I have the following configuration, but I cant figure out the URL to reach the HelloWorldXml method.

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

What would be the proper URL to use? http://localhost:8787/products/MyName.xml returns a 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)
}

英文:
 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)
}

huangapple
  • 本文由 发表于 2013年9月10日 21:38:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/18720526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定