72 lines
2.6 KiB
Go
72 lines
2.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/felixge/httpsnoop"
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"lincodex/backend/internal/adapter/primary/http/observe"
|
|
)
|
|
|
|
// unmatchedRoute names a request that matched no route.
|
|
const unmatchedRoute = "unmatched"
|
|
|
|
// RequestMetrics records one finished request. route is a route template,
|
|
// never the raw path.
|
|
type RequestMetrics interface {
|
|
ObserveRequest(method, route string, status int, duration time.Duration)
|
|
}
|
|
|
|
// ProblemMetrics is the optional part of a RequestMetrics collector that also
|
|
// counts error responses by the problem code they carry. A collector without
|
|
// it still gets every request.
|
|
type ProblemMetrics interface {
|
|
ObserveProblem(route, problemCode string)
|
|
}
|
|
|
|
// RouteResolver refines the chi route pattern of a request, for example into
|
|
// the path template of a generated operation mounted under a wildcard. It
|
|
// must return a template from a fixed set, never a value taken from the
|
|
// request path. It returns pattern unchanged when it has nothing better.
|
|
type RouteResolver func(r *http.Request, pattern string) string
|
|
|
|
// routeTemplate returns the bounded route of a finished request: the chi
|
|
// pattern refined by resolve, or unmatchedRoute. chi keeps the route context
|
|
// of the request as a pointer, so the pattern matched downstream is visible
|
|
// through the request that entered the middleware.
|
|
func routeTemplate(r *http.Request, resolve RouteResolver) string {
|
|
var route string
|
|
if routing := chi.RouteContext(r.Context()); routing != nil {
|
|
route = routing.RoutePattern()
|
|
}
|
|
if resolve != nil {
|
|
route = resolve(r, route)
|
|
}
|
|
if route == "" {
|
|
return unmatchedRoute
|
|
}
|
|
return route
|
|
}
|
|
|
|
// CollectMetrics observes every request with its route template, status,
|
|
// and duration, and, when metrics implements ProblemMetrics, every error
|
|
// response with the problem code it carries. resolve may be nil.
|
|
func CollectMetrics(metrics RequestMetrics, resolve RouteResolver) func(http.Handler) http.Handler {
|
|
problems, countsProblems := metrics.(ProblemMetrics)
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
ctx, observed := observe.Ensure(r.Context())
|
|
captured := httpsnoop.CaptureMetrics(next, w, r.WithContext(ctx))
|
|
route := routeTemplate(r, resolve)
|
|
metrics.ObserveRequest(r.Method, route, captured.Code, captured.Duration)
|
|
// A problem built for a response that finally succeeded is not
|
|
// an error of this request.
|
|
if code := observed.ProblemCode(); countsProblems && captured.Code >= http.StatusBadRequest && code != "" {
|
|
problems.ObserveProblem(route, code)
|
|
}
|
|
})
|
|
}
|
|
}
|