github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/middleware/stats.go (about) 1 package middleware 2 3 import ( 4 "net/http" 5 6 "github.com/felixge/httpsnoop" 7 "github.com/hellofresh/janus/pkg/metrics" 8 "github.com/hellofresh/stats-go/client" 9 "github.com/hellofresh/stats-go/timer" 10 log "github.com/sirupsen/logrus" 11 ) 12 13 const ( 14 notFoundPath = "/-not-found-" 15 statsSectionRoundTrip = "round" 16 ) 17 18 // Stats represents the stats middleware 19 type Stats struct { 20 statsClient client.Client 21 } 22 23 // NewStats creates a new instance of Stats 24 func NewStats(statsClient client.Client) *Stats { 25 return &Stats{statsClient} 26 } 27 28 // Handler is the middleware function 29 func (m *Stats) Handler(handler http.Handler) http.Handler { 30 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 31 log.WithField("path", r.URL.Path).Debug("Starting Stats middleware") 32 r = r.WithContext(metrics.NewContext(r.Context(), m.statsClient)) 33 34 mt := httpsnoop.CaptureMetrics(handler, w, r) 35 t := timer.NewDuration(mt.Duration) 36 37 success := mt.Code < http.StatusBadRequest 38 if mt.Code == http.StatusNotFound { 39 log.WithField("path", r.URL.Path).Warn("Unknown endpoint requested") 40 r.URL.Path = notFoundPath 41 } 42 m.statsClient.TrackRequest(r, t, success) 43 44 m.statsClient.SetHTTPRequestSection(statsSectionRoundTrip). 45 TrackRequest(r, t, mt.Code < http.StatusInternalServerError). 46 ResetHTTPRequestSection() 47 }) 48 }