Files
mtusi2026lab6/backend/internal/httpapi/middleware/otel.go
T

79 lines
2.6 KiB
Go

package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
"high-loud-apps-labs/internal/telemetry"
)
// OTel создаёт серверный span для каждого HTTP-запроса.
//
// Имя span: "<METHOD> <route_template>", например "GET /api/v1/chats/:chat_id".
// Родительский контекст извлекается из заголовков W3C traceparent чтобы связать внешний клиент (или LB) с внутренними спанами.
func OTel() gin.HandlerFunc {
tracer := telemetry.Tracer("httpapi")
return func(c *gin.Context) {
// 1. Извлекаем родительский контекст из заголовков
parentCtx := otel.GetTextMapPropagator().Extract(
c.Request.Context(),
propagation.HeaderCarrier(c.Request.Header),
)
// 2. Стартуем span с временным именем (route ещё неизвестен)
ctx, span := tracer.Start(parentCtx,
c.Request.Method+" unknown",
trace.WithSpanKind(trace.SpanKindServer),
)
defer span.End()
// 3. Кладём контекст в запрос, чтобы дочерние спаны (БД, S3, Redis) видели родителя
c.Request = c.Request.WithContext(ctx)
// 4. Базовые атрибуты, известные до выполнения handler
span.SetAttributes(
attribute.String("http.request.method", c.Request.Method),
attribute.String("url.path", c.Request.URL.Path),
attribute.String("url.scheme", scheme(c)),
attribute.String("server.address", c.Request.Host),
attribute.String("client.address", c.ClientIP()),
attribute.String("user_agent.original", c.Request.UserAgent()),
)
// 5. Выполняем цепочку middleware и handler
c.Next()
// 6. После выполнения знаем route template — обновляем имя span
route := c.FullPath()
if route == "" {
route = "unknown"
}
span.SetName(c.Request.Method + " " + route)
span.SetAttributes(attribute.String("http.route", route))
// 7. Статус ответа
status := c.Writer.Status()
span.SetAttributes(attribute.Int("http.response.status_code", status))
if status >= 500 {
span.SetStatus(codes.Error, http.StatusText(status))
}
}
}
func scheme(c *gin.Context) string {
if c.Request.TLS != nil {
return "https"
}
if v := c.GetHeader("X-Forwarded-Proto"); v != "" {
return v
}
return "http"
}