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) {
            ...
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据