如何在同一个应用程序中使用 gorilla websocket 和 mux?

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


蓝山帝景
浏览 148回答 1
1回答

万千封印

函数的第二个参数类型http.ListenAndServe是http.Handler,如果他为nil,http lib使用http.DefaultServeMuxhttp.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 示例不使用 http.HandleFunc 函数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go