为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
蓝山帝景 2022-05-23 18:08:53
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
查看完整描述

1 回答

?
万千封印

TA贡献1891条经验 获得超3个赞

函数的第二个参数类型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 函数。


查看完整回答
反对 回复 2022-05-23
  • 1 回答
  • 0 关注
  • 147 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号