-
Notifications
You must be signed in to change notification settings - Fork 137
/
utils.go
219 lines (199 loc) · 5.04 KB
/
utils.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package utils
import (
"fmt"
"math/rand"
"net"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"unicode/utf8"
"golang.org/x/net/idna"
)
func init() {
// So that we do not generate the same IDs upon restart
rand.Seed(time.Now().UTC().UnixNano())
}
// RandomString returns a string of random alpha characters of the specified
// length.
func RandomString(n int) string {
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, n)
lenLetters := len(letters)
for i := 0; i < n; i++ {
b[i] = letters[rand.Intn(lenLetters)]
}
return string(b)
}
// RandomStringFast returns a random string containing printable ascii
// characters: [0-9a-zA-Z_-]{n}. Each character encodes 6bits of entropy. To
// avoid wasting entropy, it is better to create a string whose length is a
// multiple of 10. For instance a 20 bytes string will encode 120 bits of
// entropy.
func RandomStringFast(rng *rand.Rand, n int) string {
// extract 10 letters — 60 bits of entropy — for each pseudo-random uint64
const K = 10
const L = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"
b := make([]byte, ((n+K-1)/K)*K)
for i := 0; i < n; i += K {
rn := rng.Uint64()
for j := 0; j < K; j++ {
b[i+j] = L[rn&0x3F]
rn >>= 6
}
}
return string(b[:n])
}
// IsInArray returns whether or not a string is in the given array of strings.
func IsInArray(s string, a []string) bool {
for _, ss := range a {
if s == ss {
return true
}
}
return false
}
// StripPort extract the domain name from a domain:port string.
func StripPort(domain string) string {
if strings.Contains(domain, ":") {
cleaned, _, err := net.SplitHostPort(domain)
if err != nil {
return domain
}
return cleaned
}
return domain
}
// CookieDomain removes the port and does IDNA encoding.
func CookieDomain(domain string) string {
domain = StripPort(domain)
ascii, err := idna.ToASCII(domain)
if err != nil {
return domain
}
return ascii
}
// SplitTrimString slices s into all substrings a s separated by sep, like
// strings.Split. In addition it will trim all those substrings and filter out
// the empty ones.
func SplitTrimString(s, sep string) []string {
if s == "" {
return []string{}
}
return TrimStrings(strings.Split(s, sep))
}
// TrimStrings trim all strings and filter out the empty ones.
func TrimStrings(strs []string) []string {
filteredStrs := strs[:0]
for _, part := range strs {
part = strings.TrimSpace(part)
if part != "" {
filteredStrs = append(filteredStrs, part)
}
}
return filteredStrs
}
// UniqueStrings returns a filtered slice without string duplicates.
func UniqueStrings(strs []string) []string {
filteredStrs := strs[:0]
for _, str1 := range strs {
found := false
for _, str2 := range filteredStrs {
if str1 == str2 {
found = true
break
}
}
if !found {
filteredStrs = append(filteredStrs, str1)
}
}
return filteredStrs
}
// FileExists returns whether or not the file exists on the current file
// system.
func FileExists(name string) (bool, error) {
infos, err := os.Stat(name)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
if infos.IsDir() {
return false, fmt.Errorf("Path %s is a directory", name)
}
return true, nil
}
// DirExists returns whether or not the directory exists on the current file
// system.
func DirExists(name string) (bool, error) {
infos, err := os.Stat(name)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
if !infos.IsDir() {
return false, fmt.Errorf("Path %s is not a directory", name)
}
return true, nil
}
// AbsPath returns an absolute path relative.
func AbsPath(inPath string) string {
if strings.HasPrefix(inPath, "~") {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
inPath = home + inPath[len("~"):]
} else if strings.HasPrefix(inPath, "$HOME") {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
inPath = home + inPath[len("$HOME"):]
}
if strings.HasPrefix(inPath, "$") {
end := strings.Index(inPath, string(os.PathSeparator))
inPath = os.Getenv(inPath[1:end]) + inPath[end:]
}
p, err := filepath.Abs(inPath)
if err == nil {
return filepath.Clean(p)
}
return ""
}
// CleanUTF8 returns a string with only valid UTF-8 runes
func CleanUTF8(s string) string {
if utf8.ValidString(s) {
return s
}
v := make([]rune, 0, len(s))
for _, r := range s {
if r != utf8.RuneError {
v = append(v, r)
}
}
return string(v)
}
// CloneURL clones the given url
func CloneURL(u *url.URL) *url.URL {
clone := *u
if clone.User != nil {
tmp := *clone.User
clone.User = &tmp
}
return &clone
}
// DurationFuzzing returns a duration that is near the given duration, but
// randomized to avoid patterns like several cache entries that expires at the
// same time.
func DurationFuzzing(d time.Duration, variation float64) time.Duration {
if variation > 1.0 || variation < 0.0 {
panic("DurationRandomized: variation should be between 0.0 and 1.0")
}
return time.Duration(float64(d) * (1.0 + variation*(2.0*rand.Float64()-1.0)))
}