propagator.go 1.6 KB

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