-
-
Notifications
You must be signed in to change notification settings - Fork 352
/
utils.go
359 lines (297 loc) · 6.9 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package utils
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
mr "math/rand"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"sync"
"text/template"
"time"
"github.com/tidwall/gjson"
)
// Nil type
type Nil struct{}
// E if the last arg is error, panic it
func E(args ...interface{}) []interface{} {
err, ok := args[len(args)-1].(error)
if ok {
panic(err)
}
return args
}
// SDump a value
func SDump(v interface{}) string {
d, err := json.MarshalIndent(v, "", " ")
E(err)
return string(d)
}
// Dump values to logger
func Dump(list ...interface{}) {
out := []string{}
for _, v := range list {
out = append(out, SDump(v))
}
log.Println(strings.Join(out, " "))
}
// S Template render, the params is key-value pairs
func S(tpl string, params ...interface{}) string {
var out bytes.Buffer
dict := map[string]interface{}{}
fnDict := template.FuncMap{}
l := len(params)
for i := 0; i < l-1; i += 2 {
k := params[i].(string)
v := params[i+1]
if reflect.TypeOf(v).Kind() == reflect.Func {
fnDict[k] = v
} else {
dict[k] = v
}
}
t := template.Must(template.New("").Funcs(fnDict).Parse(tpl))
E(t.Execute(&out, dict))
return out.String()
}
// RandString generate random string with specified string length
func RandString(len int) string {
b := make([]byte, len)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
// Mkdir makes dir recursively
func Mkdir(path string) error {
return os.MkdirAll(path, 0775)
}
// OutputFile auto creates file if not exists, it will try to detect the data type and
// auto output binary, string or json
func OutputFile(p string, data interface{}) error {
dir := filepath.Dir(p)
_ = Mkdir(dir)
var bin []byte
switch t := data.(type) {
case []byte:
bin = t
case string:
bin = []byte(t)
default:
bin = MustToJSONBytes(data)
}
return ioutil.WriteFile(p, bin, 0664)
}
// ReadString reads file as string
func ReadString(p string) (string, error) {
bin, err := ioutil.ReadFile(p)
return string(bin), err
}
// All run all actions concurrently, returns the wait function for all actions.
func All(actions ...func()) func() {
wg := &sync.WaitGroup{}
wg.Add(len(actions))
runner := func(action func()) {
defer wg.Done()
action()
}
for _, action := range actions {
go runner(action)
}
return wg.Wait
}
// Sleep the goroutine for specified seconds, such as 2.3 seconds
func Sleep(seconds float64) {
d := time.Duration(seconds * float64(time.Second))
time.Sleep(d)
}
// Sleeper sleeps for sometime, returns the reason to wake, if ctx is done release resource
type Sleeper func(context.Context) error
// CountSleeper wake when counts to max and return
func CountSleeper(max int) Sleeper {
count := 0
return func(ctx context.Context) error {
if ctx.Err() != nil {
return ctx.Err()
}
if count == max {
return errors.New("max sleep count")
}
count++
return nil
}
}
// DefaultBackoff algorithm: A(n) = A(n-1) * random[1.9, 2.1)
func DefaultBackoff(interval time.Duration) time.Duration {
scale := 2 + (mr.Float64()-0.5)*0.2
return time.Duration(float64(interval) * scale)
}
// BackoffSleeper returns a sleeper that sleeps in a backoff manner every time get called.
// If algorithm is nil, DefaultBackoff will be used.
// Set interval and maxInterval to the same value to make it a constant interval sleeper.
// If maxInterval is not greater than 0, it will wake immediately.
func BackoffSleeper(init, maxInterval time.Duration, algorithm func(time.Duration) time.Duration) Sleeper {
if algorithm == nil {
algorithm = DefaultBackoff
}
return func(ctx context.Context) error {
// wake immediately
if maxInterval <= 0 {
return nil
}
var interval time.Duration
if init < maxInterval {
interval = algorithm(init)
} else {
interval = maxInterval
}
t := time.NewTicker(interval)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
init = interval
}
return nil
}
}
// Retry fn and sleeper until fn returns true or s returns error
func Retry(ctx context.Context, s Sleeper, fn func() (stop bool, err error)) error {
for {
stop, err := fn()
if stop {
return err
}
err = s(ctx)
if err != nil {
return err
}
}
}
var chPause = make(chan struct{})
// Pause the goroutine forever
func Pause() {
<-chPause
}
// IsSyncMapEmpty helper
func IsSyncMapEmpty(s *sync.Map) bool {
isEmpty := true
s.Range(func(key, value interface{}) bool {
isEmpty = false
return false
})
return isEmpty
}
// SyncMapToMap convertor
func SyncMapToMap(s *sync.Map) map[string]interface{} {
m := map[string]interface{}{}
s.Range(func(key, value interface{}) bool {
m[fmt.Sprintf("%v", key)] = value
return false
})
return m
}
// MustToJSONBytes encode data to json bytes
func MustToJSONBytes(data interface{}) []byte {
bytes, err := json.Marshal(data)
E(err)
return bytes
}
// MustToJSON encode data to json string
func MustToJSON(data interface{}) string {
return string(MustToJSONBytes(data))
}
// FileExists checks if file exists, only for file, not for dir
func FileExists(path string) bool {
info, err := os.Stat(path)
if err != nil {
return false
}
if info.IsDir() {
return false
}
return true
}
// Exec command
func Exec(name string, args ...string) {
cmd := exec.Command(name, args...)
SetCmdStdPipe(cmd)
E(cmd.Run())
}
// SetCmdStdPipe command
func SetCmdStdPipe(cmd *exec.Cmd) {
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
}
type errMuxWrapper struct {
mux *http.ServeMux
}
// ServeHTTP interface
func (h *errMuxWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
w.WriteHeader(http.StatusBadRequest)
E(w.Write([]byte(fmt.Sprint(err))))
}
}()
h.mux.ServeHTTP(w, r)
}
// Serve a port, if host is empty a random port will be used.
func Serve(host string) (string, *http.ServeMux, func()) {
if host == "" {
host = "127.0.0.1:0"
}
mux := http.NewServeMux()
srv := &http.Server{Handler: &errMuxWrapper{mux}}
l, err := net.Listen("tcp", host)
E(err)
go func() { _ = srv.Serve(l) }()
url := "http://" + l.Addr().String()
return url, mux, func() {
E(srv.Close())
}
}
// ReadJSON from reader
func ReadJSON(r io.Reader) (gjson.Result, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return gjson.Result{}, err
}
return gjson.ParseBytes(b), nil
}
// ReadJSONPathAsString from reader
func ReadJSONPathAsString(r io.Reader, path string) (string, error) {
obj, err := ReadJSON(r)
if err != nil {
return "", err
}
return obj.Get(path).String(), nil
}
// MustReadJSON from reader
func MustReadJSON(r io.Reader) gjson.Result {
j, err := ReadJSON(r)
E(err)
return j
}
// MustReadBytes from reader
func MustReadBytes(r io.Reader) []byte {
b, err := ioutil.ReadAll(r)
E(err)
return b
}
// MustReadString from reader
func MustReadString(r io.Reader) string {
return string(MustReadBytes(r))
}