Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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
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.
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.