-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathkey.go
114 lines (91 loc) · 2.49 KB
/
key.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
// Copyright 2018-21 PJ Engineering and Business Solutions Pty. Ltd. All rights reserved.
package remember
import (
"bytes"
"encoding/json"
"fmt"
"hash/crc32"
"reflect"
"runtime"
"strings"
)
// CreateKey will generate a key based on the input arguments.
// When prefix is true, the caller's name will be used to prefix the key in an attempt to make it unique.
// The args can also be separated using sep. visual performs no functionality. It is used at code level
// to visually see how the key is structured.
func CreateKey(prefix bool, sep string, visual string, args ...interface{}) string {
var output string
if prefix {
pc, file, line, ok := runtime.Caller(1)
if !ok {
return fmt.Sprint(args...)
}
details := runtime.FuncForPC(pc)
output = fmt.Sprintf("%s_%s_%d_", details.Name(), file, line)
}
if sep == "" {
output = output + fmt.Sprint(args...)
} else {
for i, v := range args {
if i != 0 {
output = output + sep
}
output = output + fmt.Sprint(v)
}
}
return output
}
// Hash returns a crc32 hashed version of key.
func Hash(key string) string {
return fmt.Sprintf("%08x", crc32.ChecksumIEEE([]byte(key)))
}
// CreateKeyStruct generates a key by converting a struct into a JSON object.
func CreateKeyStruct(strct interface{}) string {
out := map[string]interface{}{}
// Encode nil immediately
if strct == nil {
return ""
}
s := reflect.ValueOf(strct)
// Check if s is a pointer
if s.Kind() == reflect.Ptr {
s = reflect.Indirect(s)
}
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := typeOfT.Field(i)
if f.PkgPath != "" {
// Not exported
continue
}
fieldName := typeOfT.Field(i).Name
fieldTag := f.Tag.Get("json")
fieldValRaw := s.Field(i)
fieldVal := fieldValRaw.Interface()
// Ignore slices
if fieldValRaw.Kind() == reflect.Slice {
continue
}
// Check if json parser would ordinarily hide the value anyway
if fieldTag == "-" || (strings.HasSuffix(fieldTag, ",omitempty") && reflect.DeepEqual(fieldVal, reflect.Zero(reflect.TypeOf(fieldVal)).Interface())) {
continue
}
if fieldTag == "" {
out[fieldName] = fieldVal
} else {
out[strings.TrimSuffix(fieldTag, ",omitempty")] = fieldVal
}
}
b, _ := json.Marshal(out)
str, _ := compactJson(b)
return str
}
// compactJson will remove insignificant spaces to minimize storage space.
func compactJson(src []byte) (string, error) {
dst := new(bytes.Buffer)
err := json.Compact(dst, src)
if err != nil {
return "", err
}
return dst.String(), nil
}