英文:
Gorilla Mux not handling my path
问题
当我使用http
的默认路由器时,一切正常工作,但如果我使用gorilla/mux
的路由器,我会得到一个带有内容为404 page not found
的404页面。如下面的示例所示,其他部分完全相同。
为什么gorilla/mux
的路由器不像这样工作?
使用http
路由器正确工作的示例:
package main
import "net/http"
func simplestPossible(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("MWE says OK"))
}
func main() {
http.HandleFunc("/", simplestPossible)
http.ListenAndServe(":8000", nil)
}
使用gorilla/mux
路由器不工作的示例:
package main
import "net/http"
import "github.com/gorilla/mux"
func simplestPossible(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("MWE says OK"))
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", simplestPossible)
http.ListenAndServe(":8000", nil)
}
英文:
When I use the default router from http
everything works, but if I use the router from gorilla/mux
instead, I get a 404 page with the body 404 page not found
. As shown in the samples below, everything else is exactly the same.
Why doesn't the gorilla/mux
router work like this?
Working correctly, using http
routing:
package main
import "net/http"
func simplestPossible(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("MWE says OK"))
}
func main() {
http.HandleFunc("/", simplestPossible)
http.ListenAndServe(":8000", nil)
}
Not working, using gorilla/mux
routing:
package main
import "net/http"
import "github.com/gorilla/mux"
func simplestPossible(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("MWE says OK"))
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", simplestPossible)
http.ListenAndServe(":8000", nil)
}
答案1
得分: 2
你必须将你的处理程序传递给http包的ListenAndServe函数:
http.ListenAndServe(":8000", r)
英文:
You must pass your handler to http package (ListenAndServe):
<!-- language: go -->
http.ListenAndServe(":8000", r)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论