登录
首页 >  Golang >  Go问答

结合使用 gorilla websocket 和 mux 的教程

来源:stackoverflow

时间:2024-02-26 13:39:26 439浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《结合使用 gorilla websocket 和 mux 的教程》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

问题内容

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对象,你需要合并注册的路由请求两个路由器。

    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函数。

以上就是《结合使用 gorilla websocket 和 mux 的教程》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>