Search code examples
gogorilla

How to use gorilla websocket and mux in the same application?


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)
    }
}

With the above code, the /api route gives a 404. But if I change the err := http.ListenAndServe(":8000", nill) to err := http.ListenAndServe(":8000", router), the /api route works but the / route (which I serve the frontend) gives a 404.

How do I make them both work?

Edit: full code - https://codeshare.io/2Kpyb8


Solution

  • The second parameter type of the http.ListenAndServe function is http.Handler, if he is nil, http lib use http.DefaultServeMux http.Handler.

    your /api route register to mux.NewRouter(), your / and /ws route register to http.DefaultServeMux,These are two different http.Handler objetc, You need to merge the routing requests registered by the two routers.

        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 not use http.HandleFunc function.