/
utils.go
89 lines (79 loc) · 1.5 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
package goutils
import (
"bytes"
"encoding/json"
"errors"
"reflect"
"math/rand"
"time"
)
// Determine if the variable is null
func Empty(arg interface{}) bool {
if arg == nil {
return true
}
v := reflect.ValueOf(arg)
switch v.Kind() {
case reflect.Slice, reflect.Map, reflect.Array:
if v.Len() > 0 {
return false
}
return true
case reflect.Ptr:
v = v.Elem()
}
return v.Interface() == reflect.Zero(v.Type()).Interface()
}
// Returns a formatted Json string
func Export(v interface{}) string {
b, err := json.Marshal(v)
if err != nil {
return ""
}
var buf bytes.Buffer
err = json.Indent(&buf, b, "", "\t")
if err != nil {
return ""
}
return buf.String()
}
// Returns a Json string
func Json(v interface{}) string {
b, err := json.Marshal(v)
if err != nil {
return ""
}
return string(b)
}
func Decode(s string) interface{} {
var i interface{}
err := json.Unmarshal([]byte(s), &i)
if err != nil {
return nil
}
return i
}
func Unmarshal(s string, args ...interface{}) error {
if len(args) == 0 {
return errors.New("the second parameter is required.")
}
err := json.Unmarshal([]byte(s), &args[0])
if err != nil {
return err
}
return nil
}
// utils.If(c).Then(v).Else(v).String()
func If(c bool) *ifThen {
return new(ifThen).If(c)
}
func Then(v interface{}) *ifThen {
return new(ifThen).Then(v)
}
func Else(v interface{}) *ifThen {
return new(ifThen).Else(v)
}
// GenerateNonce -
func GenerateNonce() int {
return 100000 + rand.Intn(int(time.Now().UnixNano()%1000000))
}