forked from sas1024/gorm-loggable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathidentity_manager.go
51 lines (41 loc) · 925 Bytes
/
identity_manager.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
package loggable
import (
"crypto/md5"
"encoding/hex"
"fmt"
"github.com/jinzhu/copier"
"reflect"
)
type identityMap map[string]interface{}
// identityManager is used as cache.
type identityManager struct {
m identityMap
}
func newIdentityManager() *identityManager {
return &identityManager{
m: make(identityMap),
}
}
func (im *identityManager) save(value, pk interface{}) {
t := reflect.TypeOf(value)
newValue := reflect.New(t).Interface()
err := copier.Copy(&newValue, value)
if err != nil {
panic(err)
}
im.m[genIdentityKey(t, pk)] = newValue
}
func (im identityManager) get(value, pk interface{}) interface{} {
t := reflect.TypeOf(value)
key := genIdentityKey(t, pk)
m, ok := im.m[key]
if !ok {
return nil
}
return m
}
func genIdentityKey(t reflect.Type, pk interface{}) string {
key := fmt.Sprintf("%v_%s", pk, t.Name())
b := md5.Sum([]byte(key))
return hex.EncodeToString(b[:])
}