1
votes

If I have a mux.Router, how do I set it to be a "subrouter"? All examples I can find creates a new router by calling Route.Subrouter() and then setting Handlers on it, but I already have a router!

// does not know about "/api/v1/"
v1_router := mux.NewRouter()
subrouter.HandleFuc("/route1/", ...)
subrouter.HandleFuc("/route2/", ...)

// does not now about route1, route2
r := mux.NewRouter()
r.PathPrefix("/api/v1/").???(v1_router)

I hope I'm making sense...

2
Can't you just call subrouter.PathPrefix?kopiczko
And how subrouter is created?kopiczko
@kopiczko then the subrouter has to know the pathprefix which I don't wantRikard
meanwhile, I make due with creating a router via SubRouter and passing it to a "RegisterRoutes" methodRikard

2 Answers

0
votes

I feel the same way, and have to live with the same "workaround". I would like to set the subrouter to an existing router. Like:

r.PathPrefix("/api").SetSubrouter(api.GetRouter()) //won't work

That would let my api feel more autonomous / loosely coupled. But getting a subrouter is all we have from gorilla.

s := r.PathPrefix("/api").Subrouter()
api.SetRoutes(s)
0
votes

You can do it like this:

v1 package file:

func Handlers(subrouter *mux.Router) {
    //base handler, i.e. /v1
    r.StrictSlash(true)
    subrouter.HandleFuc("/route1/", ...)
    subrouter.HandleFuc("/route2/", ...)
}

main file:

r := mux.NewRouter()
package.Handlers(r.PathPrefix("/api/v1").Subrouter())