-
Notifications
You must be signed in to change notification settings - Fork 55
/
util.go
86 lines (78 loc) · 1.51 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
// Package zutil daily development helper functions
package zutil
import (
"fmt"
"os"
"runtime"
"sync"
"time"
)
func WithLockContext(mu *sync.Mutex, fn func()) {
mu.Lock()
defer mu.Unlock()
fn()
}
func WithRunTimeContext(handler func()) time.Duration {
start := time.Now()
handler()
return time.Since(start)
}
func WithRunMemContext(handler func()) uint64 {
var mem = runtime.MemStats{}
runtime.ReadMemStats(&mem)
curMem := mem.TotalAlloc
handler()
runtime.ReadMemStats(&mem)
return mem.TotalAlloc - curMem
}
// IfVal Simulate ternary calculations, pay attention to handling no variables or indexing problems
func IfVal(condition bool, trueVal, falseVal interface{}) interface{} {
if condition {
return trueVal
}
return falseVal
}
// TryCatch exception capture
func TryCatch(fn func() error) (err error) {
defer func() {
if recoverErr := recover(); recoverErr != nil {
if e, ok := recoverErr.(error); ok {
err = e
} else {
err = fmt.Errorf("%v", recoverErr)
}
}
}()
err = fn()
return
}
// Deprecated: please use TryCatch
// Try exception capture
func Try(fn func(), catch func(e interface{}), finally ...func()) {
if len(finally) > 0 {
defer func() {
finally[0]()
}()
}
defer func() {
if err := recover(); err != nil {
if catch != nil {
catch(err)
} else {
panic(err)
}
}
}()
fn()
}
// CheckErr CheckErr
func CheckErr(err error, exit ...bool) {
if err != nil {
if len(exit) > 0 && exit[0] {
fmt.Println(err)
os.Exit(1)
return
}
panic(err)
}
}