【问题标题】:How to use gorilla websocket and mux in the same application?如何在同一个应用程序中使用 gorilla websocket 和 mux?
【发布时间】:2020-04-11 00:37:23
【问题描述】:
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

【问题讨论】:

    标签: go gorilla


    【解决方案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 example 不使用 http.HandleFunc 函数。

    【讨论】:

    • “/”路由仍然不起作用,没有提供任何静态文件。
    • 我不使用 gorilla/mux,不确定路由 //* 匹配所有请求,例如 / 可以计算所有请求 uri。你的404是文件未找到,不是路由404。os.Open没有文件返回404,权限被拒绝返回403。静态文件参考forum.golangbridge.org/t/…
    • 研究了以下通配符匹配。正确的代码是router.PathPrefix("/").Handler(http.FileServer(http.Dir("../public")))。 mux 库与其他库框架不同。混沌设计界面。
    • /ws 向上移动'/*'?我修改了原来的答案
    • /* 路由和通配符路由将覆盖 mux 和 httprouter 中的其他路由。 /*包含/ws路径,所以要注意路由注册的顺序。
    猜你喜欢
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    相关资源
    最近更新 更多