Skip to content

Commit

Permalink
fix: avoid creating a new endpoint in prometheus for each urls
Browse files Browse the repository at this point in the history
  • Loading branch information
thoas committed Sep 26, 2023
1 parent 8a43973 commit 4ec3652
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
22 changes: 17 additions & 5 deletions middleware/metrics.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
package middleware

import (
"context"
"fmt"

"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
)

type RouteKey struct{}

func Route(route string) gin.HandlerFunc {
return func(c *gin.Context) {
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), RouteKey{}, route))
c.Next()
}
}

func Metrics(c *gin.Context) {
c.Next()
customMetrics.histogram.WithLabelValues(
c.Request.Method,
c.Request.URL.String(),
fmt.Sprint(c.Writer.Status()))

route, ok := c.Request.Context().Value(RouteKey{}).(string)
if ok {
customMetrics.histogram.WithLabelValues(
c.Request.Method,
route,
fmt.Sprint(c.Writer.Status()))
}
}

var customMetrics = newMetrics()
Expand Down
4 changes: 4 additions & 0 deletions server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,19 @@ func (s *HTTPServer) Init() error {
pattern: "redirect",
handler: failure.Handle(handlers.redirect),
method: router.GET,
route: "redirect",
},
{
pattern: "display",
handler: failure.Handle(handlers.display),
method: router.GET,
route: "display",
},
{
pattern: "get",
handler: failure.Handle(handlers.get),
method: router.GET,
route: "get",
},
}
)
Expand Down Expand Up @@ -146,6 +149,7 @@ func (s *HTTPServer) Init() error {
middleware.URLParser(s.config.Options.MimetypeDetector, s.processor),
middleware.OperationParser(),
middleware.RestrictSizes(s.config.Options.AllowedSizes),
middleware.Route(e.route),
e.handler,
}

Expand Down
1 change: 1 addition & 0 deletions server/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ type endpoint struct {
handler gin.HandlerFunc
method handlerMethod
pattern string
route string
}

0 comments on commit 4ec3652

Please sign in to comment.