trace.go 736 B

123456789101112131415161718192021222324252627
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/opentracing/opentracing-go"
  5. )
  6. // Trace 链路追踪
  7. func Trace() gin.HandlerFunc {
  8. return func(ctx *gin.Context) {
  9. var sp opentracing.Span
  10. opName := ctx.Request.URL.Path
  11. // Attempt to join a trace by getting trace context from the headers.
  12. wireContext, err := opentracing.GlobalTracer().Extract(
  13. opentracing.TextMap,
  14. opentracing.HTTPHeadersCarrier(ctx.Request.Header))
  15. if err != nil {
  16. // If for whatever reason we can't join, go ahead an start a new root span.
  17. sp = opentracing.StartSpan(opName)
  18. } else {
  19. sp = opentracing.StartSpan(opName, opentracing.ChildOf(wireContext))
  20. }
  21. ctx.Set("traceSpan", sp)
  22. ctx.Next()
  23. sp.Finish()
  24. }
  25. }