dscdttg4389 2014-10-30 12:34
浏览 17
已采纳

来自处理程序内部的Gorilla Mux路由器仅工作一次,然后显示404页未找到

I'm using Gorilla mux as my router and I'm having a very strange behaviour. On the first request to the server, I get a valid response. But on subsequent requests, I receive a 404 page not found. There are no errors in the console.

My code is pretty straightforward (it can be copy-pasted to test it right out):

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)
}

After some code commenting and tests, it seems the following line is the culprit:

rootUrl, err := mux.CurrentRoute(r).Subrouter().Get("root").URL()

This method of getting the router inside the handler using the current request comes from another StackOverflow post: How to call a route by its name from inside a handler?

But for a strange reason, it only works once:

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

As you can see, there are no errors in the console.

Does someone have an idea of why it only works once ?

  • 写回答

1条回答 默认 最新

  • dpq39825 2014-10-30 14:07
    关注

    The problem is Subrouter() isn't made to return the router, but to create one, thus it changes the matcher of the router it is called on, making you lose the handler.

    You could try passing the router to the handler using closures instead.

    func RootHandler(router *mux.Router) func(http.ResponseWriter, *http.Request) {
        return func(w http.ResponseWriter, r *http.Request) {
            ...
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路