Skip to content

Instantly share code, notes, and snippets.

@juanpabloaj
Last active February 28, 2019 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanpabloaj/896c2abaa4d74fd289bf4ef103581aff to your computer and use it in GitHub Desktop.
Save juanpabloaj/896c2abaa4d74fd289bf4ef103581aff to your computer and use it in GitHub Desktop.
show mux routes
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
type RoutesResponse struct {
Routes []string `json:"routes"`
}
type Service struct {
Router *mux.Router
}
func (s *Service) handler(w http.ResponseWriter, r *http.Request) {
return
}
func (s *Service) routes(w http.ResponseWriter, r *http.Request) {
routes := []string{}
s.Router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
t, err := route.GetPathTemplate()
if err != nil {
return err
}
log.Println(t)
routes = append(routes, t)
return nil
})
js, _ := json.Marshal(RoutesResponse{
Routes: routes,
})
w.Header().Set("Content-Type", "application/json")
w.Write(js)
return
}
func main() {
service := Service{
Router: mux.NewRouter(),
}
service.Router.HandleFunc("/articles", service.handler).Methods("GET")
service.Router.HandleFunc("/articles/{id}", service.handler).Methods("GET")
service.Router.HandleFunc("/routes", service.routes).Methods("GET")
log.Printf("running ...")
log.Fatal(http.ListenAndServe(":8080", service.Router))
}
@juanpabloaj
Copy link
Author

curl localhost:8080/routes | python -m json.tool
{
    "routes": [
        "/articles",
        "/articles/{id}",
        "/routes"
    ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment