我使用 Gorillamux作为我的路由器,我的行为非常奇怪。在对服务器的第一个请求中,我得到了一个有效的响应。但在随后的请求中,我收到了一个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 帖子:如何从处理程序内部通过其名称调用路由?
但出于一个奇怪的原因,它只工作一次:
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
如您所见,控制台中没有错误。
有人知道为什么它只能工作一次吗?