Skip to content

Commit

Permalink
fix: don't ignore stats middleware template path calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
atzoum committed Oct 19, 2022
1 parent a194b0c commit 130c9af
Showing 1 changed file with 32 additions and 6 deletions.
38 changes: 32 additions & 6 deletions middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package middleware
import (
"context"
"net/http"
"strconv"
"sync/atomic"
"time"

Expand Down Expand Up @@ -52,23 +53,48 @@ func StatMiddleware(ctx context.Context, router *mux.Router) func(http.Handler)
getPath := func(r *http.Request) string {
var match mux.RouteMatch
if router.Match(r, &match) {
if path, err := match.Route.GetPathTemplate(); err != nil {
if path, err := match.Route.GetPathTemplate(); err == nil {
return path
}
}
return r.URL.Path
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sw := newStatusCapturingWriter(w)
path := getPath(r)
latencyStat := stats.Default.NewSampledTaggedStat("gateway.response_time", stats.TimerType, map[string]string{"reqType": path, "method": r.Method})
latencyStat.Start()
defer latencyStat.End()

start := time.Now()
atomic.AddInt32(&concurrentRequests, 1)
defer atomic.AddInt32(&concurrentRequests, -1)

next.ServeHTTP(w, r)
next.ServeHTTP(sw, r)

stats.Default.NewSampledTaggedStat(
"gateway.response_time",
stats.TimerType,
map[string]string{
"reqType": path,
"method": r.Method,
"code": strconv.Itoa(sw.status),
}).Since(start)
})
}
}

type statusCapturingWriter struct {
http.ResponseWriter
status int
}

func newStatusCapturingWriter(w http.ResponseWriter) *statusCapturingWriter {
return &statusCapturingWriter{
ResponseWriter: w,
status: http.StatusOK,
}
}

// WriteHeader override the http.ResponseWriter's `WriteHeader` method
func (w *statusCapturingWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}

0 comments on commit 130c9af

Please sign in to comment.