-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
75 lines (62 loc) · 1.42 KB
/
cache.go
File metadata and controls
75 lines (62 loc) · 1.42 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
package cache
import (
"context"
"encoding/json"
"log"
"time"
)
// Cacher that adapter needs to implement
type Cacher interface {
Get(ctx context.Context, key string) (string, error)
Set(ctx context.Context, key string, data string, expire time.Duration) error
Delete(ctx context.Context, key string) error
}
type Options struct {
expire time.Duration
}
type Option func(*Options)
// WithExpire sets the expire time for the cache
func WithExpire(expire time.Duration) Option {
return func(o *Options) {
o.expire = expire
}
}
// Cache caches the data which is returned by fn with the given key
func Cache[T any](ctx context.Context, c Cacher, key string, fn func() (T, error), opts ...Option) (T, error) {
var data T
options := &Options{
expire: 30 * time.Minute,
}
for _, opt := range opts {
opt(options)
}
if info, err := c.Get(ctx, key); err == nil {
return unmarshal[T](info)
}
data, err := fn()
if err != nil {
return data, err
}
val, err := marshal(data)
if err != nil {
return data, err
}
if err := c.Set(ctx, key, val, options.expire); err != nil {
log.Println("[cache] set error:", err)
}
return data, nil
}
func marshal(data any) (string, error) {
b, err := json.Marshal(data)
if err != nil {
return "", err
}
return string(b), nil
}
func unmarshal[T any](data string) (T, error) {
var m T
if err := json.Unmarshal([]byte(data), &m); err != nil {
return m, err
}
return m, nil
}