英文:
GAE Golang Gorilla mux - 404 page not found
问题
我在GAE中使用gorilla mux遇到了一些问题。
当我尝试使用它时,我得到了'404页面未找到'的错误。rootHandler函数没有被调用(没有生成任何迹象)
以下是我的代码的一部分,有什么想法吗?
提前感谢
...
    func init() {
     r := mux.NewRouter()
     r.HandleFunc("/",rootHandler)
    }
    func rootHandler(w http.ResponseWriter, r *http.Request) {
     var functionName = "rootHandler"
     c := appengine.NewContext(r)
     c.Infof(functionName+"-start")
     defer c.Infof(functionName+"-end")
...
英文:
I've got some problems to use gorilla mux within GAE.
When I try it, I've '404 page not found'. The rootHandler function is not called ( no traces generated)
Below is part of my code, any ideas?
thk in advance
...
    func init() {
     r := mux.NewRouter()
     r.HandleFunc("/",rootHandler)
    }
    func rootHandler(w http.ResponseWriter, r *http.Request) {
     var functionName = "rootHandler"
     c := appengine.NewContext(r)
     c.Infof(functionName+"-start")
     defer c.Infof(functionName+"-end")
...
答案1
得分: 32
你必须将请求路由到你的mux路由器上。http包有一个DefaultServeMux,它被AppEngine使用,但mux没有。(而且它不会自己将其路由注册到net/http中)
也就是说,你所要做的就是将你的mux路由器注册到net/http中:
func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    r.HandleFunc("/products", ProductsHandler)
    r.HandleFunc("/articles", ArticlesHandler)
    http.Handle("/", r)
}
(直接来自文档)
这里重要的部分是http.Handle("/", r)。
英文:
You have to route requests to your mux router. http package has DefaultServeMux which is used by AppEngine, but mux does not. (and it's not registering its routes with net/http by itself)
That is, all you have to do, is register your mux router with net/http:
func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    r.HandleFunc("/products", ProductsHandler)
    r.HandleFunc("/articles", ArticlesHandler)
    http.Handle("/", r)
}
(straight from the docs)
Important part here is http.Handle("/", r).
答案2
得分: 2
你也可以将路由器作为第二个参数传递给ListenAndServe,因为它实现了http.Handler接口。
router := mux.NewRouter()
router.HandleFunc("/", HomeHandler)
http.ListenAndServe(":8080", router) // 在这里传递路由器
英文:
You can also pass the router as the second argument to ListenAndServe since it implements the http.Handler interface.
router := mux.NewRouter()
router.HandleFunc("/", HomeHandler)
http.ListenAndServe(":8080", router) // pass the router here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论