-
Notifications
You must be signed in to change notification settings - Fork 55
/
util.go
61 lines (55 loc) · 1.02 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
// Package zutil daily development helper functions
package zutil
import (
"fmt"
"os"
"sync"
"time"
)
func WithLockContext(fn func()) {
var mu sync.Mutex
mu.Lock()
defer mu.Unlock()
fn()
}
func WithRunTimeContext(closer func(), callback func(time.Duration)) {
start := time.Now()
closer()
timeduration := time.Since(start)
callback(timeduration)
}
// 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
}
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)
}
}