我正在使用大猩猩mux
作为我的路由器,我的行为非常奇怪。在向服务器发出第一个请求时,我得到了有效的响应。但在随后的请求中,我收到了404 page not found
。控制台中没有错误。
我的代码非常简单(可以复制粘贴来立即测试):
package main
import (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/", RootHandler).Name("root")
http.Handle("/", router)
log.Println("Listening on port 1337...")
if err := http.ListenAndServe(":1337", nil); err != nil {
log.Fatal("http.ListenAndServe: ", err)
}
}
func RootHandler(w http.ResponseWriter, r *http.Request) {
content := "Welcome to "
rootUrl, err := mux.CurrentRoute(r).Subrouter().Get("root").URL()
if err != nil {
log.Printf("mux.CurrentRoute(r).Subrouter().Get(\"root\").URL(): ", err)
}
response := content + rootUrl.String()
fmt.Fprintf(w, response)
}
经过一些代码注释和测试后,似乎以下行是罪魁祸首:
rootUrl, err := mux.CurrentRoute(r).Subrouter().Get("root").URL()
这种使用当前请求在处理程序中获取路由器的方法来自另一个 StackOverflow 帖子:如何从处理程序内部按名称调用路由? https://stackoverflow.com/questions/23553061/how-to-call-a-route-by-its-name-from-inside-a-handler
但由于一个奇怪的原因,它只起作用一次:
shell-1$ go run servertest.go
2014/10/30 13:31:34 Listening on port 1337...
shell-2$ curl http://127.0.0.1:1337
Welcome to /
shell-2$ curl http://127.0.0.1:1337
404 page not found
正如您所看到的,控制台中没有错误。
有人知道为什么吗它只起作用once ?
问题是 Subrouter() 不是为了返回路由器,而是为了创建一个路由器,因此它会更改所调用的路由器的匹配器,从而使您丢失处理程序。
您可以尝试使用闭包将路由器传递给处理程序。
func RootHandler(router *mux.Router) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
...
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)