49 lines
1.3 KiB
Go
49 lines
1.3 KiB
Go
package middlewares
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"gitea.konchin.com/go2025/backend/utils"
|
|
"github.com/uptrace/bunrouter"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
func BunrouterOtel(next bunrouter.HandlerFunc) bunrouter.HandlerFunc {
|
|
return func(w http.ResponseWriter, req bunrouter.Request) error {
|
|
span := trace.SpanFromContext(req.Context())
|
|
if !span.IsRecording() {
|
|
return next(w, req)
|
|
}
|
|
|
|
params := req.Params()
|
|
span.SetName(req.Method + " " + params.Route())
|
|
|
|
paramSlice := params.Slice()
|
|
attrs := make([]attribute.KeyValue, 0, 3+len(paramSlice))
|
|
|
|
attrs = append(attrs, semconv.HTTPRouteKey.String(req.Route()))
|
|
|
|
if req.URL != nil {
|
|
attrs = append(attrs, semconv.HTTPTargetKey.String(req.URL.RequestURI()))
|
|
} else {
|
|
// This should never occur if the request was generated by the net/http
|
|
// package. Fail gracefully, if it does though.
|
|
attrs = append(attrs, semconv.HTTPTargetKey.String(req.RequestURI))
|
|
}
|
|
|
|
attrs = append(attrs, semconv.HTTPClientIPKey.String(
|
|
utils.GetRemoteAddr(req)))
|
|
|
|
for _, param := range paramSlice {
|
|
attrs = append(attrs, attribute.String("http.route.param."+param.Key,
|
|
param.Value))
|
|
}
|
|
|
|
span.SetAttributes(attrs...)
|
|
|
|
return next(w, req)
|
|
}
|
|
}
|