-
Notifications
You must be signed in to change notification settings - Fork 2
/
cached.go
64 lines (53 loc) · 1.27 KB
/
cached.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
package introspector
import (
"encoding/json"
"errors"
"fmt"
)
// Cached allows you to query multiple introspector
type Cached struct {
Introspector Introspector
Cache interface {
Get(key string) ([]byte, error)
Set(key string, entry []byte) error
}
}
type result struct {
I Introspection
Err string
}
// Introspect returns a cached version of the introspection of the token
func (c Cached) Introspect(token string) (i Introspection, err error) {
res := result{}
// Attempt to retrieve from cache
data, err := c.Cache.Get("introspect:" + token)
if err == nil {
err = json.Unmarshal(data, &res)
if err != nil {
return res.I, fmt.Errorf("unmarshal %s from cache: %w", string(data), err)
}
return res.I, errOrNil(res.Err)
}
// Retrieve from Introspector
res.I, err = c.Introspector.Introspect(token)
if err != nil {
res.Err = err.Error()
}
// Marshal data
data, err = json.Marshal(res)
if err != nil {
return res.I, fmt.Errorf("marshal %+v to cache: %w", res, err)
}
// Save in cache
err = c.Cache.Set("introspect:"+token, data)
if err != nil {
return res.I, fmt.Errorf("save %s in cache: %w", string(data), err)
}
return res.I, errOrNil(res.Err)
}
func errOrNil(str string) error {
if str == "" {
return nil
}
return errors.New(str)
}