-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshared_metadata.go
More file actions
85 lines (75 loc) · 1.86 KB
/
Copy pathshared_metadata.go
File metadata and controls
85 lines (75 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package gin
import (
sync
)
// SharedMetadataKey is the key used to store the shared metadata in the context.
const SharedMetadataKey = "_gin_shared_metadata_"
// SharedMetadata is a thread-safe map for sharing metadata between copied contexts.
type SharedMetadata struct {
mu sync.RWMutex
m map[string]any
}
// NewSharedMetadata creates a new SharedMetadata instance.
func NewSharedMetadata() *SharedMetadata {
return &SharedMetadata{
m: make(map[string]any),
}
}
// Set sets a key-value pair in the shared metadata.
func (s *SharedMetadata) Set(key string, value any) {
s.mu.Lock()
s.m[key] = value
s.mu.Unlock()
}
// Get retrieves a value from the shared metadata.
func (s *SharedMetadata) Get(key string) (any, bool) {
s.mu.RLock()
val, ok := s.m[key]
s.mu.RUnlock()
return val, ok
}
// Map returns a copy of the underlying map.
func (s *SharedMetadata) Map() map[string]any {
s.mu.RLock()
defer s.mu.RUnlock()
cp := make(map[string]any, len(s.m))
for k, v := range s.m {
cp[k] = v
}
return cp
}
// SetShared sets a key-value pair in the shared metadata.
// If the shared metadata map does not exist in the context, it will be initialized.
func (c *Context) SetShared(key string, value any) {
c.mu.Lock()
if c.Keys == nil {
c.Keys = make(map[string]any)
}
var shared *SharedMetadata
if val, ok := c.Keys[SharedMetadataKey]; ok {
shared, _ = val.(*SharedMetadata)
}
if shared == nil {
shared = NewSharedMetadata()
c.Keys[SharedMetadataKey] = shared
}
c.mu.Unlock()
shared.Set(key, value)
}
// GetShared retrieves a value from the shared metadata.
func (c *Context) GetShared(key string) (any, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
if c.Keys == nil {
return nil, false
}
val, ok := c.Keys[SharedMetadataKey]
if !ok {
return nil, false
}
shared, ok := val.(*SharedMetadata)
if !ok {
return nil, false
}
return shared.Get(key)
}