propagator.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package trace
  2. import (
  3. "net/http"
  4. "google.golang.org/grpc/metadata"
  5. )
  6. const (
  7. // HttpFormat means http carrier format.
  8. HttpFormat = iota
  9. // GrpcFormat means grpc carrier format.
  10. GrpcFormat
  11. )
  12. var (
  13. emptyHttpPropagator httpPropagator
  14. emptyGrpcPropagator grpcPropagator
  15. )
  16. type (
  17. // Propagator interface wraps the Extract and Inject methods.
  18. Propagator interface {
  19. Extract(carrier interface{}) (Carrier, error)
  20. Inject(carrier interface{}) (Carrier, error)
  21. }
  22. httpPropagator struct{}
  23. grpcPropagator struct{}
  24. )
  25. func (h httpPropagator) Extract(carrier interface{}) (Carrier, error) {
  26. if c, ok := carrier.(http.Header); ok {
  27. return httpCarrier(c), nil
  28. }
  29. return nil, ErrInvalidCarrier
  30. }
  31. func (h httpPropagator) Inject(carrier interface{}) (Carrier, error) {
  32. if c, ok := carrier.(http.Header); ok {
  33. return httpCarrier(c), nil
  34. }
  35. return nil, ErrInvalidCarrier
  36. }
  37. func (g grpcPropagator) Extract(carrier interface{}) (Carrier, error) {
  38. if c, ok := carrier.(metadata.MD); ok {
  39. return grpcCarrier(c), nil
  40. }
  41. return nil, ErrInvalidCarrier
  42. }
  43. func (g grpcPropagator) Inject(carrier interface{}) (Carrier, error) {
  44. if c, ok := carrier.(metadata.MD); ok {
  45. return grpcCarrier(c), nil
  46. }
  47. return nil, ErrInvalidCarrier
  48. }
  49. // Extract extracts tracing information from carrier with given format.
  50. func Extract(format, carrier interface{}) (Carrier, error) {
  51. switch v := format.(type) {
  52. case int:
  53. if v == HttpFormat {
  54. return emptyHttpPropagator.Extract(carrier)
  55. } else if v == GrpcFormat {
  56. return emptyGrpcPropagator.Extract(carrier)
  57. }
  58. }
  59. return nil, ErrInvalidCarrier
  60. }
  61. // Inject injects tracing information into carrier with given format.
  62. func Inject(format, carrier interface{}) (Carrier, error) {
  63. switch v := format.(type) {
  64. case int:
  65. if v == HttpFormat {
  66. return emptyHttpPropagator.Inject(carrier)
  67. } else if v == GrpcFormat {
  68. return emptyGrpcPropagator.Inject(carrier)
  69. }
  70. }
  71. return nil, ErrInvalidCarrier
  72. }