-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom.go
210 lines (165 loc) · 4.57 KB
/
custom.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package caching
import (
"errors"
"log"
"net/http"
"time"
"github.com/labstack/echo/v4"
"github.com/golang-common-packages/hash"
"github.com/golang-common-packages/linear"
)
// CustomClient manage all custom caching action
type CustomClient struct {
client *linear.Client
close chan struct{}
}
// NewCustom init new instance
func NewCustom(config *Config) ICaching {
currentSession := &CustomClient{linear.New(config.CustomCache.CacheSize, config.CustomCache.CleaningEnable), make(chan struct{})}
// Check record expiration time and remove
go func() {
ticker := time.NewTicker(config.CustomCache.CleaningInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
items := currentSession.client.GetItems()
items.Range(func(key, value interface{}) bool {
item := value.(customCacheItem)
if item.expires < time.Now().UnixNano() {
k, _ := key.(string)
currentSession.client.Get(k)
}
return true
})
case <-currentSession.close:
return
}
}
}()
return currentSession
}
// Middleware for echo framework
func (cl *CustomClient) Middleware(hash hash.IHash) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
token := c.Request().Header.Get(echo.HeaderAuthorization)
key := hash.SHA512(token)
if val, err := cl.Get(key); err != nil {
log.Printf("Can not get accesstoken from custom caching in echo middleware: %s", err.Error())
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
} else if val == "" {
return c.NoContent(http.StatusUnauthorized)
}
return next(c)
}
}
}
// Get return value based on the key provided
func (cl *CustomClient) Get(key string) (interface{}, error) {
if key == "" {
return nil, errors.New("key must not empty")
}
obj, err := cl.client.Read(key)
if err != nil {
return nil, err
}
item, ok := obj.(customCacheItem)
if !ok {
return nil, errors.New("can not map object to customCacheItem model")
}
if item.expires < time.Now().UnixNano() {
return nil, nil
}
return item.data, nil
}
// Get return value based on the list of keys provided
func (cl *CustomClient) GetMany(keys []string) (map[string]interface{}, []string, error) {
if len(keys) == 0 {
return nil, nil, errors.New("keys must not empty")
}
var itemFound map[string]interface{}
var itemNotFound []string
for _, key := range keys {
obj, err := cl.client.Read(key)
if obj == nil && err == nil {
itemNotFound = append(itemNotFound, key)
}
item, ok := obj.(customCacheItem)
if !ok {
return nil, nil, errors.New("can not map object to customCacheItem model")
}
itemFound[key] = item.data
}
return itemFound, itemNotFound, nil
}
// Set new record set key and value
func (cl *CustomClient) Set(key string, value interface{}, expire time.Duration) error {
if key == "" || value == nil {
return errors.New("key and value must not empty")
}
if expire == 0 {
expire = 24 * time.Hour
}
if err := cl.client.Push(key, customCacheItem{
data: value,
expires: time.Now().Add(expire).UnixNano(),
}); err != nil {
return err
}
return nil
}
// Update new value over the key provided
func (cl *CustomClient) Update(key string, value interface{}, expire time.Duration) error {
if key == "" || value == nil {
return errors.New("key and value must not empty")
}
_, err := cl.client.Get(key)
if err != nil {
return err
}
if expire == 0 {
expire = 24 * time.Hour
}
if err := cl.client.Push(key, customCacheItem{
data: value,
expires: time.Now().Add(expire).UnixNano(),
}); err != nil {
return err
}
return nil
}
// Delete deletes the key and its value from the cache.
func (cl *CustomClient) Delete(key string) error {
if key == "" {
return errors.New("key must not empty")
}
if _, err := cl.client.Get(key); err != nil {
return err
}
return nil
}
// Range over linear data structure
func (cl *CustomClient) Range(f func(key, value interface{}) bool) {
fn := func(key, value interface{}) bool {
item := value.(customCacheItem)
if item.expires > 0 && item.expires < time.Now().UnixNano() {
return true
}
return f(key, item.data)
}
cl.client.Range(fn)
}
// GetNumberOfRecords return number of records
func (cl *CustomClient) GetNumberOfRecords() int {
return cl.client.GetNumberOfKeys()
}
// GetDBSize method return redis database size
func (cl *CustomClient) GetCapacity() (interface{}, error) {
return cl.client.GetLinearCurrentSize(), nil
}
// Close closes the cache and frees up resources.
func (cl *CustomClient) Close() error {
cl.close <- struct{}{}
return nil
}