propagator.go 1.7 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 nil, ErrInvalidCarrier
  25. } else {
  26. return httpCarrier(c), nil
  27. }
  28. }
  29. func (h httpPropagator) Inject(carrier interface{}) (Carrier, error) {
  30. if c, ok := carrier.(http.Header); ok {
  31. return httpCarrier(c), nil
  32. } else {
  33. return nil, ErrInvalidCarrier
  34. }
  35. }
  36. func (g grpcPropagator) Extract(carrier interface{}) (Carrier, error) {
  37. if c, ok := carrier.(metadata.MD); ok {
  38. return grpcCarrier(c), nil
  39. } else {
  40. return nil, ErrInvalidCarrier
  41. }
  42. }
  43. func (g grpcPropagator) Inject(carrier interface{}) (Carrier, error) {
  44. if c, ok := carrier.(metadata.MD); ok {
  45. return grpcCarrier(c), nil
  46. } else {
  47. return nil, ErrInvalidCarrier
  48. }
  49. }
  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. func Inject(format, carrier interface{}) (Carrier, error) {
  62. switch v := format.(type) {
  63. case int:
  64. if v == HttpFormat {
  65. return emptyHttpPropagator.Inject(carrier)
  66. } else if v == GrpcFormat {
  67. return emptyGrpcPropagator.Inject(carrier)
  68. }
  69. }
  70. return nil, ErrInvalidCarrier
  71. }