Files
mtusi2026lab6/internal/httpapi/middleware.go
T

78 lines
3.0 KiB
Go

package httpapi
import (
"net/http"
"strconv"
"strings"
"github.com/felixge/httpsnoop"
"go.opentelemetry.io/otel/attribute"
otellog "go.opentelemetry.io/otel/log"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
"mtusi2026/internal/store"
"mtusi2026/internal/telemetry"
)
var (
httpRequests, _ = telemetry.Meter.Int64Counter("messenger.http.requests")
httpDuration, _ = telemetry.Meter.Float64Histogram("messenger.http.request.duration",
metric.WithUnit("s"),
metric.WithExplicitBucketBoundaries(.001, .0025, .005, .01, .025, .05, .1, .25, .5, 1, 2, 4, 8, 15, 30, 60))
)
func observeRequests(root, apiMux *http.ServeMux) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, pattern := root.Handler(r)
if pattern == "GET /health/live" || pattern == "GET /health/ready" {
root.ServeHTTP(w, r)
return
}
_, pattern = apiMux.Handler(r)
registeredMethod, route, matched := strings.Cut(pattern, " ")
if !matched || (registeredMethod != r.Method && !(r.Method == http.MethodHead && registeredMethod == http.MethodGet)) {
route = "<unmatched>"
}
method := r.Method
switch method {
case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch,
http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace:
default:
method = "_OTHER"
}
ctx := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
ctx, span := telemetry.Tracer.Start(ctx, method+" "+route, trace.WithSpanKind(trace.SpanKindServer),
trace.WithAttributes(attribute.String("http.request.method", method), attribute.String("http.route", route)))
defer span.End()
result := httpsnoop.CaptureMetrics(root, w, r.WithContext(ctx))
statusClass := strconv.Itoa(result.Code/100) + "xx"
attrs := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route),
attribute.String("status_class", statusClass))
httpRequests.Add(ctx, 1, attrs)
httpDuration.Record(ctx, result.Duration.Seconds(), attrs)
span.SetAttributes(attribute.Int("http.response.status_code", result.Code))
severity := otellog.SeverityInfo
if result.Code >= 500 {
severity = otellog.SeverityError
telemetry.SetError(span, statusClass)
}
telemetry.Event(ctx, severity, "http.request",
otellog.String("method", method), otellog.String("route", route), otellog.Int("http.status_code", result.Code),
otellog.Float64("duration_s", result.Duration.Seconds()), otellog.String("request_id", w.Header().Get("X-Request-Id")))
})
}
func concurrencyMiddleware(limiter *store.Limiter, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !limiter.TryAcquire() {
requestID := newRequestID()
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "сервер перегружен, попробуйте позже")
return
}
defer limiter.Release()
next.ServeHTTP(w, r)
})
}