mirror of
https://github.com/3ybactuk/marketplace-go-service-project.git
synced 2025-10-30 14:03:45 +03:00
[hw-7] add metrics, tracing
This commit is contained in:
38
cart/internal/infra/http/middlewares/metrics.go
Normal file
38
cart/internal/infra/http/middlewares/metrics.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"route256/cart/internal/infra/http/metrics"
|
||||
)
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(code int) {
|
||||
w.statusCode = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func NewMetricsMiddleware(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sw := &statusWriter{
|
||||
ResponseWriter: w,
|
||||
statusCode: http.StatusOK,
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
h.ServeHTTP(sw, r)
|
||||
|
||||
path := r.URL.Path
|
||||
status := strconv.Itoa(sw.statusCode)
|
||||
|
||||
metrics.IncRequestHandlerCount(r.Method, path, status)
|
||||
metrics.StoreHandlerRequestDuration(r.Method, path, status, time.Since(start))
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user