-
Notifications
You must be signed in to change notification settings - Fork 20
/
utils.go
427 lines (379 loc) · 7.53 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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package ppp
import (
"crypto/md5"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"golang.org/x/crypto/pkcs12"
"io"
"io/ioutil"
"math"
"net"
"net/http"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"time"
)
// LoadPrivateKeyFromFile 从文件中加载私钥
func LoadPrivateKeyFromFile(file string) (key *rsa.PrivateKey, err error) {
private, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
key, err = x509.ParsePKCS1PrivateKey(base64Decode(string(private)))
return
}
// LoadPublicKeyFromFile 从文件中加载公钥
func LoadPublicKeyFromFile(file string) (key *rsa.PublicKey, err error) {
public, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
block, _ := pem.Decode(public)
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
key, _ = pub.(*rsa.PublicKey)
return
}
// LoadCertFromP12 从p12中加载证书
func LoadCertFromP12(file, pwd string) (cert tls.Certificate, err error) {
b, err := ioutil.ReadFile(file)
if err != nil {
return cert, err
}
blocks, err := pkcs12.ToPEM(b, pwd)
if err != nil {
return cert, err
}
var pemData []byte
for _, b := range blocks {
pemData = append(pemData, pem.EncodeToMemory(b)...)
}
cert, err = tls.X509KeyPair(pemData, pemData)
return
}
/**
timeid
*/
type U struct {
prefix string
c chan int
d chan struct{}
}
func NewU(t int64, n int) *U {
u := &U{
prefix: time.Unix(t, 0).Format("060102150405"),
c: make(chan int, n),
d: make(chan struct{}),
}
u.start()
return u
}
func (u *U) start() {
go func() {
i := 0
for {
select {
case u.c <- i:
i++
case <-u.d:
return
}
}
}()
}
func (u *U) stop() {
u.d <- struct{}{}
close(u.c)
}
func (u *U) Next() string {
return u.prefix + fmt.Sprintf("%d", <-u.c)
}
type TimeID struct {
o *U
c *U
n *U
l int
}
func NewTimeID(l int) *TimeID {
return &TimeID{l: l}
}
func (u *TimeID) Start() error {
go func() {
t := time.NewTicker(time.Second)
u.n = NewU(time.Now().Unix(), u.l)
for {
u.o = u.c
u.c = u.n
u.n = NewU(time.Now().Unix()+1, u.l)
if u.o != nil {
u.o.stop()
}
<-t.C
}
}()
for u.c == nil {
time.Sleep(1 * time.Millisecond)
}
return nil
}
func (u *TimeID) Next() string {
return u.c.Next()
}
var _systemID *TimeID
func init() {
_systemID = NewTimeID(10)
_systemID.Start()
}
func randomTimeString() string {
return _systemID.Next()
}
/**
字符串md5
*/
func makeMd5(str string) string {
h := md5.New()
io.WriteString(h, str)
s := fmt.Sprintf("%x", h.Sum(nil))
return s
}
/**
生成随机字符串
*/
func randomString(lens int) string {
now := time.Now()
return makeMd5(strconv.FormatInt(now.UnixNano(), 10))[:lens]
}
/**
转化时间戳
*/
func str2Sec(layout, str string) int64 {
tm2, _ := time.ParseInLocation(layout, str, time.Local)
return tm2.Unix()
}
/**
时间戳格式化
*/
func sec2Str(layout string, sec int64) string {
t := time.Unix(sec, 0)
nt := t.Format(layout)
return nt
}
/**
获取当前时间戳
*/
func getNowSec() int64 {
return time.Now().Unix()
}
/**
压json
*/
func jsonEncode(ob interface{}) []byte {
if b, err := json.Marshal(ob); err == nil {
return b
}
return []byte("")
}
/**
解json
*/
func jsonDecode(data []byte, ob interface{}) error {
return json.Unmarshal(data, ob)
}
var base64Base = base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
/**
压base64
*/
func base64Encode(data []byte) string {
return base64Base.EncodeToString(data)
}
/**
解base64
*/
func base64Decode(src string) []byte {
byt, err := base64Base.DecodeString(src)
if err != nil {
return []byte{}
}
return byt
}
/**
将struct转化为map,tag:json,xml
*/
func structToMap(obj interface{}, tag string) map[string]string {
t := reflect.TypeOf(obj)
v := reflect.ValueOf(obj)
m := map[string]string{}
for i := 0; i < t.NumField(); i++ {
fv := v.Field(i)
t := t.Field(i).Tag.Get(tag)
switch v.Field(i).Interface().(type) {
case string:
m[t] = fv.String()
case int, int64:
m[t] = strconv.FormatInt(fv.Int(), 10)
}
}
return m
}
/**
map排序
*/
type mapSorter []sortItem
type sortItem struct {
Key string `json:"key"`
Val interface{} `json:"val"`
}
func (ms mapSorter) Len() int {
return len(ms)
}
func (ms mapSorter) Less(i, j int) bool {
return ms[i].Key < ms[j].Key // 按键排序
}
func (ms mapSorter) Swap(i, j int) {
ms[i], ms[j] = ms[j], ms[i]
}
/**
map排序并根据排序结果kv拼接,empty:是否去除空值
*/
func mapSortAndJoin(m map[string]string, step1, step2 string, empty bool) string {
ms := make(mapSorter, 0, len(m))
for k, v := range m {
ms = append(ms, sortItem{k, v})
}
sort.Sort(ms)
s := []string{}
for _, p := range ms {
if p.Val.(string) != "" || !empty {
s = append(s, p.Key+step1+p.Val.(string))
}
}
return strings.Join(s, step2)
}
func parseFloat(s string) float64 {
f, _ := strconv.ParseFloat(s, 64)
return f
}
// float64 四舍五入取整
func round(x float64) int64 {
return int64(math.Round(x))
}
/**
Urlencode
*/
func httpBuildQuery(params map[string]string) string {
qs := url.Values{}
for k, v := range params {
qs.Add(k, v)
}
return qs.Encode()
}
/*
发送带有超时的Get请求
*/
func getRequest(url string) ([]byte, error) {
client := timeoutClient()
resp, err := client.Get(url)
if err != nil {
fmt.Println("GetRequest:", url, "Error:", err.Error())
return nil, err
}
defer resp.Body.Close()
respbody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return respbody, nil
}
/*
发送带有超时的Post请求
*/
func postRequest(url, contentType string, body io.Reader) ([]byte, error) {
client := timeoutClient()
resp, err := client.Post(url, contentType, body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respbody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return respbody, nil
}
/*
发送带有超时的Post https请求
*/
func postRequestTLS(url, contentType string, body io.Reader, tlsConfig *tls.Config) ([]byte, error) {
client := timeoutClientWithTLS(tlsConfig)
resp, err := client.Post(url, contentType, body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respbody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return respbody, nil
}
const (
maxTimeout int64 = 25
connectTimeout time.Duration = 3 * time.Second
readWriteTimeout time.Duration = 5 * time.Second
)
/**
网络请求链接定义
*/
func timeoutClient() *http.Client {
return &http.Client{
Transport: &http.Transport{
Dial: timeoutDialer(connectTimeout, readWriteTimeout),
MaxIdleConnsPerHost: 200,
DisableKeepAlives: true,
},
}
}
/**
网络请求链接定义
*/
func timeoutClientWithTLS(tlsConfig *tls.Config) *http.Client {
return &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
Dial: timeoutDialer(connectTimeout, readWriteTimeout),
MaxIdleConnsPerHost: 200,
DisableKeepAlives: true,
},
}
}
func timeoutDialer(cTimeout time.Duration,
rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) {
return func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, cTimeout)
if err != nil {
return nil, err
}
conn.SetDeadline(time.Now().Add(rwTimeout))
return conn, nil
}
}
func newError(msg string) error {
return errors.New(msg)
}
func newErrorByE(e Error) error {
if e.Code == Succ {
return nil
}
return newError(e.Msg)
}