I’m constructing my API router inside a function
package api
import "net/http"
func New() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /ping", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
// other routes go here...
return mux
}
and I want every route to have the route prefix /api
. Do I have to create a subrouter for this like so?
// ...
apiRouter := http.NewServeMux()
// let the apiRouter instance handle all routes now
apiRouter.HandleFunc("GET /ping", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
mux.Handle("/api/", http.StripPrefix("/api", apiRouter))
// ...
so I’m basically a new router instance inside the mux instance. But is there a simpler way to achieve this? This approach feels weird because I have to nest an additional router instance.