metadata.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package middleware
  2. // MetadataReader provides an interface for reading metadata from the
  3. // underlying metadata container.
  4. type MetadataReader interface {
  5. Get(key interface{}) interface{}
  6. }
  7. // Metadata provides storing and reading metadata values. Keys may be any
  8. // comparable value type. Get and set will panic if key is not a comparable
  9. // value type.
  10. //
  11. // Metadata uses lazy initialization, and Set method must be called as an
  12. // addressable value, or pointer. Not doing so may cause key/value pair to not
  13. // be set.
  14. type Metadata struct {
  15. values map[interface{}]interface{}
  16. }
  17. // Get attempts to retrieve the value the key points to. Returns nil if the
  18. // key was not found.
  19. //
  20. // Panics if key type is not comparable.
  21. func (m Metadata) Get(key interface{}) interface{} {
  22. return m.values[key]
  23. }
  24. // Clone creates a shallow copy of Metadata entries, returning a new Metadata
  25. // value with the original entries copied into it.
  26. func (m Metadata) Clone() Metadata {
  27. vs := make(map[interface{}]interface{}, len(m.values))
  28. for k, v := range m.values {
  29. vs[k] = v
  30. }
  31. return Metadata{
  32. values: vs,
  33. }
  34. }
  35. // Set stores the value pointed to by the key. If a value already exists at
  36. // that key it will be replaced with the new value.
  37. //
  38. // Set method must be called as an addressable value, or pointer. If Set is not
  39. // called as an addressable value or pointer, the key value pair being set may
  40. // be lost.
  41. //
  42. // Panics if the key type is not comparable.
  43. func (m *Metadata) Set(key, value interface{}) {
  44. if m.values == nil {
  45. m.values = map[interface{}]interface{}{}
  46. }
  47. m.values[key] = value
  48. }
  49. // Has returns whether the key exists in the metadata.
  50. //
  51. // Panics if the key type is not comparable.
  52. func (m Metadata) Has(key interface{}) bool {
  53. if m.values == nil {
  54. return false
  55. }
  56. _, ok := m.values[key]
  57. return ok
  58. }