How to get available routes from the mux in go?
Asked Answered
P

1

8

I have a mux and 4 different routes.

a.Router = mux.NewRouter()

a.Router.HandleFunc("/1/query/{query}", a.sigQuery).Methods("GET")

a.Router.HandleFunc("/1/sis", a.rGet).Methods("GET")

a.Router.HandleFunc("/1/sigs", a.sigHandler).Methods("GET", "POST", "DELETE")

a.Router.HandleFunc("/1/nfeeds", a.nfeedGet).Methods("GET", "DELETE", "POST")

Is there a method where we can list the defined routes and get the methods defined on them. I was trying this way: routes := a.getRoutes() will return me a slice with all the routes, and methods := routes[1].Methods() will return the methods listed on that route. Is there a way we can achieve this?

Piselli answered 6/7, 2017 at 16:44 Comment(2)
Which package is "mux"? I don't believe that's a standard library package, and there are a whole bunch of routers for Go out there.Tensible
@Carpetsmoker It's gorilla mux.Piselli
B
12

Use the Walk method:

router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
    tpl, err1 := route.GetPathTemplate()
    met, err2 := route.GetMethods()
    fmt.Println(tpl, err1, met, err2)
    return nil
})

Alternatively, you can just put all your routes into a slice of structs and just do

for _, r := range routes {
    router.HandleFunc(r.tpl, r.func).Methods(r.methods...)
}

on the initialisation step.

Backhouse answered 6/7, 2017 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.