func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/api", home)
fs := http.FileServer(http.Dir("../public"))
http.Handle("/", fs)
http.HandleFunc("/ws", handleConnections)
go handleMessages()
log.Println("http server started on :8000")
err := http.ListenAndServe(":8000", nill)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
使用上面的代码,/ api路由给出404。
但是,如果我将
err := http.ListenAndServe(":8000", nill)
更改为err := http.ListenAndServe(":8000", router)
,则/ api路由有效,但/路由(我为前端服务)给出404。如何使它们都起作用?
编辑:完整代码-https://codeshare.io/2Kpyb8
最佳答案
http.ListenAndServe
函数的第二个参数类型是http.Handler,如果他为nil,则http lib使用http.DefaultServeMux
http.Handler。
您的/api
路由注册到mux.NewRouter()
,您的/
和/ws
路由注册到http.DefaultServeMux
,这是两个不同的http.Handler objetc,您需要合并两个路由器注册的路由请求。
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/api", home)
// move ws up, prevent '/*' from covering '/ws' in not testing mux, httprouter has this bug.
router.HandleFunc("/ws", handleConnections)
// PathPrefix("/") match '/*' request
router.PathPrefix("/").Handler(http.FileServer(http.Dir("../public")))
go handleMessages()
http.ListenAndServe(":8000", router)
gorilla/mux example不使用http.HandleFunc函数。
关于go - 如何在同一应用程序中使用 gorilla websocket和mux?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61138912/