ゴリラ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 投稿から来ています: 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
ご覧のとおり、コンソールにエラーはありません。
誰かがなぜ一度しか機能しないのか考えていますか?