add(internal): routes.Print and metrics.MountRoutes

This commit is contained in:
Tit Petric
2019-03-14 22:29:19 +01:00
parent be4faf54ed
commit df5fb8c7fc
2 changed files with 42 additions and 0 deletions
+15
View File
@@ -4,7 +4,11 @@ import (
"net/http"
"github.com/766b/chi-prometheus"
"github.com/99designs/basicauth-go"
"github.com/go-chi/chi"
"github.com/prometheus/client_golang/prometheus"
"github.com/crusttech/crust/internal/config"
)
// Middleware is the request logger that provides metrics to prometheus
@@ -16,3 +20,14 @@ func Middleware(name string) func(http.Handler) http.Handler {
func Handler() http.Handler {
return prometheus.Handler()
}
func MountRoutes(r chi.Router, opts *config.HTTP) {
if opts.Metrics {
r.Group(func(r chi.Router) {
r.Use(basicauth.New("Metrics", map[string][]string{
opts.MetricsUsername: {opts.MetricsPassword},
}))
r.Handle("/metrics", Handler())
})
}
}
+27
View File
@@ -0,0 +1,27 @@
package routes
import (
"fmt"
"runtime"
"reflect"
"github.com/go-chi/chi"
)
func Print(r chi.Router) {
var printRoutes func(chi.Routes, string, string)
printRoutes = func(r chi.Routes, indent string, prefix string) {
routes := r.Routes()
for _, route := range routes {
if route.SubRoutes != nil && len(route.SubRoutes.Routes()) > 0 {
fmt.Printf(indent+"%s - with %d handlers, %d subroutes\n", route.Pattern, len(route.Handlers), len(route.SubRoutes.Routes()))
printRoutes(route.SubRoutes, indent+"\t", prefix+route.Pattern[:len(route.Pattern)-2])
} else {
for key, fn := range route.Handlers {
fmt.Printf("%s%s\t%s -> %s\n", indent, key, prefix+route.Pattern, runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name())
}
}
}
}
printRoutes(r, "", "")
}