context.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. package audit
  2. import (
  3. "context"
  4. "strings"
  5. "github.com/google/uuid"
  6. "github.com/zeromicro/go-zero/core/trace"
  7. )
  8. // EnsureTraceAndSpanID resolves the trace/span ids from go-zero's OTel
  9. // context, generating UUID fallbacks (stored in ctx) when empty. It also
  10. // returns the caller identity from the RequestMeta, mirroring sdf-serve.
  11. func EnsureTraceAndSpanID(ctx context.Context) (context.Context, string, string, string, string, string) {
  12. traceID := trace.TraceIDFromContext(ctx)
  13. spanID := trace.SpanIDFromContext(ctx)
  14. if traceID == "" {
  15. traceID = strings.ReplaceAll(uuid.NewString(), "-", "")
  16. ctx = context.WithValue(ctx, TraceKey, traceID)
  17. }
  18. if spanID == "" {
  19. spanID = strings.ReplaceAll(uuid.NewString(), "-", "")
  20. ctx = context.WithValue(ctx, SpanKey, spanID)
  21. }
  22. requestMeta := GetRequestMeta(ctx)
  23. return ctx, traceID, spanID, requestMeta.UserId, requestMeta.UserName, requestMeta.ApiKey
  24. }
  25. // NewUUID returns a uuid string without dashes.
  26. func NewUUID() string {
  27. return strings.ReplaceAll(uuid.NewString(), "-", "")
  28. }