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