Skip to content
Permalink
Browse files

Automated way to get the matched route

  • Loading branch information...
Depado committed Oct 23, 2017
1 parent a67951f commit 16930c4ccca15c84701e033b58f084a10570e6e3
Showing with 27 additions and 2 deletions.
  1. +25 −1 prom.go
  2. +2 −1 prom_test.go
26 prom.go
@@ -20,6 +20,7 @@ type Prometheus struct {
MetricsPath string
Subsystem string
Engine *gin.Engine
PathMap map[string]string
}

// Path is an option allowing to set the metrics path when intializing with New.
@@ -65,9 +66,16 @@ func New(options ...func(*Prometheus)) *Prometheus {
if p.Engine != nil {
p.Engine.GET(p.MetricsPath, prometheusHandler())
}
p.PathMap = make(map[string]string)
return p
}

func (p *Prometheus) updatePathMap() {
for _, ri := range p.Engine.Routes() {
p.PathMap[ri.Handler] = ri.Path
}
}

func (p *Prometheus) register() {
p.reqCnt = prometheus.NewCounterVec(
prometheus.CounterOpts{
@@ -109,11 +117,27 @@ func (p *Prometheus) register() {

// Instrument is a gin middleware that can be used to generate metrics for a
// single handler
func (p *Prometheus) Instrument(path string) gin.HandlerFunc {
func (p *Prometheus) Instrument() gin.HandlerFunc {
p.updatePathMap()
return func(c *gin.Context) {
var path string
start := time.Now()
reqSz := computeApproximateRequestSize(c.Request)

if c.Request.URL.String() == p.MetricsPath {
c.Next()
return
}

if in, ok := p.PathMap[c.HandlerName()]; ok {
path = in
} else {
p.updatePathMap()
if in, ok := p.PathMap[c.HandlerName()]; ok {
path = in
}
}

c.Next()

status := strconv.Itoa(c.Writer.Status())
@@ -90,10 +90,11 @@ func TestUse(t *testing.T) {
func TestInstrument(t *testing.T) {
r := gin.New()
p := New(Engine(r))
r.Use(p.Instrument())
path := "/user/:id"
lpath := fmt.Sprintf(`path="%s"`, path)

r.GET(path, p.Instrument(path), func(c *gin.Context) {
r.GET(path, func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"id": c.Param("id")})
})

0 comments on commit 16930c4

Please sign in to comment.
You can’t perform that action at this time.