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

标签 go gorilla

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/

相关文章:

go - 在 Go 中编写通用 Binder

go - Golang slice 调整大小。在两个方向上较小,但在一个方向上可能较大?

go - Golang gorilla WebSocket包如何保证并发

go - 在 Go 中使用事务

go - 集群中 n 个 Web 服务器之间的文件同步

go - golang 上 2500 个用户的套接字异常

reactjs - 在 Gorilla Mux : 403 error on POST request 中配置 CORS

go - 使用 gorilla mux 指向域去服务器

go websockets with gorilla libs - 未知的 json 响应,所以无法映射它

go - TestMain 未运行