-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmethods.go
68 lines (58 loc) · 1.58 KB
/
methods.go
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
// Copyright (c) 2022 Dmitry Tkachenko ([email protected])
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package care
import (
"sync"
"time"
)
// Methods is representing an interface that allows to define
// the service's methods which responses you want to cache.
type Methods interface {
// Cacheable
// method - full method name
//
// Returns true and caching timeout if the method is found,
// otherwise false and timeout in this case does not matter.
Cacheable(method string) (bool, time.Duration)
// Add - allows to add method for caching.
// Returns the 'Methods' in order to be
// more convenient methods adding like a chain.
Add(method string, ttl time.Duration) Methods
// Remove the method from allowed to be cached.
Remove(method string)
// Clean - removes all methods.
Clean()
}
type methodsStorage struct {
mtx sync.RWMutex
methods map[string]time.Duration
}
func (s *methodsStorage) Cacheable(method string) (bool, time.Duration) {
s.mtx.RLock()
defer s.mtx.RUnlock()
ttl, ok := s.methods[method]
return ok, ttl
}
func (s *methodsStorage) Add(method string, ttl time.Duration) Methods {
s.mtx.Lock()
s.mtx.Unlock()
s.methods[method] = ttl
return s
}
func (s *methodsStorage) Remove(method string) {
s.mtx.Lock()
s.mtx.Unlock()
delete(s.methods, method)
}
func (s *methodsStorage) Clean() {
newMap := make(map[string]time.Duration)
s.mtx.Lock()
s.mtx.Unlock()
s.methods = newMap
}
func newMethodsStorage() Methods {
return &methodsStorage{
methods: make(map[string]time.Duration),
}
}