/
util.go
112 lines (88 loc) · 2.56 KB
/
util.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
package util
import (
"fmt"
"math"
"regexp"
"time"
"github.com/dchest/uniuri"
"github.com/spf13/cast"
)
var (
keyLengthLimit = 63
keyRegex = regexp.MustCompile(`^[\w\d-/\.\:]+$`)
valueLengthLimit = 63
valueRegex = regexp.MustCompile(`^[ \w\d-/\.\:]+$`)
randomKeyCharset = []byte("123456789abcdefghijkmnopqrstuvwxyz")
randomKeyPrefix = "k"
)
// IsSafeKey return if the key is safe to store
func IsSafeKey(s string) (bool, string) {
if !keyRegex.MatchString(s) {
return false, fmt.Sprintf("key:%s should have the format %v", s, keyRegex)
}
if len(s) > keyLengthLimit {
return false, fmt.Sprintf("key:%s cannot be longer than %d", s, keyLengthLimit)
}
return true, ""
}
// IsSafeValue return if the value is safe to store
func IsSafeValue(s string) (bool, string) {
if !valueRegex.MatchString(s) {
return false, fmt.Sprintf("value:%s should have the format %v", s, valueRegex)
}
if len(s) > valueLengthLimit {
return false, fmt.Sprintf("value:%s cannot be longer than %d", s, valueLengthLimit)
}
return true, ""
}
// NewSecureRandomKey creates a new secure random key
func NewSecureRandomKey() string {
return randomKeyPrefix + uniuri.NewLenChars(uniuri.StdLen, randomKeyCharset)
}
// SafeStringWithDefault parse an interface to string
// and set it to default value if it's empty
func SafeStringWithDefault(s interface{}, deft string) (ret string) {
ret = SafeString(s)
if ret == "" {
ret = deft
}
return ret
}
// SafeString safely cast to string
func SafeString(s interface{}) (ret string) {
return cast.ToString(s)
}
// SafeUint returns the uint of the value
func SafeUint(s interface{}) (ret uint) {
return cast.ToUint(s)
}
// Round makes the float to int conversion with rounding
func Round(f float64) int {
return int(f + math.Copysign(0.5, f))
}
// TimeNow follows RFC3339 time format
func TimeNow() string {
return time.Now().UTC().Format(time.RFC3339)
}
// Float32Ptr ...
func Float32Ptr(v float32) *float32 { return &v }
// Float64Ptr ...
func Float64Ptr(v float64) *float64 { return &v }
// IntPtr ...
func IntPtr(v int) *int { return &v }
// Int32Ptr ...
func Int32Ptr(v int32) *int32 { return &v }
// Int64Ptr ...
func Int64Ptr(v int64) *int64 { return &v }
// StringPtr ...
func StringPtr(v string) *string { return &v }
// UintPtr ...
func UintPtr(v uint) *uint { return &v }
// Uint32Ptr ...
func Uint32Ptr(v uint32) *uint32 { return &v }
// Uint64Ptr ...
func Uint64Ptr(v uint64) *uint64 { return &v }
// BoolPtr ...
func BoolPtr(v bool) *bool { return &v }
// ByteSlicePtr ...
func ByteSlicePtr(v []byte) *[]byte { return &v }