forked from nntaoli-project/goex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.go
141 lines (122 loc) · 2.33 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
package goex
import (
"bytes"
"compress/flate"
"compress/gzip"
"encoding/json"
"fmt"
"github.com/google/uuid"
"io/ioutil"
"math"
"net/url"
"strconv"
"strings"
)
func ToFloat64(v interface{}) float64 {
if v == nil {
return 0.0
}
switch v.(type) {
case float64:
return v.(float64)
case string:
vStr := v.(string)
vF, _ := strconv.ParseFloat(vStr, 64)
return vF
default:
panic("to float64 error.")
}
}
func ToInt(v interface{}) int {
if v == nil {
return 0
}
switch v.(type) {
case string:
vStr := v.(string)
vInt, _ := strconv.Atoi(vStr)
return vInt
case int:
return v.(int)
case float64:
vF := v.(float64)
return int(vF)
default:
panic("to int error.")
}
}
func ToUint64(v interface{}) uint64 {
if v == nil {
return 0
}
switch v.(type) {
case int:
return uint64(v.(int))
case float64:
return uint64((v.(float64)))
case string:
uV, _ := strconv.ParseUint(v.(string), 10, 64)
return uV
default:
panic("to uint64 error.")
}
}
func ToInt64(v interface{}) int64 {
if v == nil {
return 0
}
switch v.(type) {
case float64:
return int64(v.(float64))
default:
vv := fmt.Sprint(v)
if vv == "" {
return 0
}
vvv, err := strconv.ParseInt(vv, 0, 64)
if err != nil {
return 0
}
return vvv
}
}
func FloatToString(v float64, precision int) string {
return fmt.Sprint(FloatToFixed(v, precision))
}
func FloatToFixed(v float64, precision int) float64 {
p := math.Pow(10, float64(precision))
return math.Round(v*p) / p
}
func ValuesToJson(v url.Values) ([]byte, error) {
parammap := make(map[string]interface{})
for k, vv := range v {
if len(vv) == 1 {
parammap[k] = vv[0]
} else {
parammap[k] = vv
}
}
return json.Marshal(parammap)
}
func MergeOptionalParameter(values *url.Values, opts ...OptionalParameter) url.Values {
for _, opt := range opts {
for k, v := range opt {
values.Set(k, fmt.Sprint(v))
}
}
return *values
}
func GzipDecompress(data []byte) ([]byte, error) {
r, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return nil, err
}
return ioutil.ReadAll(r)
}
func FlateDecompress(data []byte) ([]byte, error) {
return ioutil.ReadAll(flate.NewReader(bytes.NewReader(data)))
}
func GenerateOrderClientId(size int) string {
uuidStr := strings.Replace(uuid.New().String(), "-", "", 32)
return "goex" + uuidStr[0:size-5]
}