This repository has been archived by the owner on Sep 23, 2021. It is now read-only.
forked from rpip/upvest-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
109 lines (90 loc) · 2.32 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
package upvest
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/url"
"path"
"reflect"
"strings"
"time"
"github.com/google/go-querystring/query"
"github.com/mitchellh/mapstructure"
)
func mapstruct(data interface{}, v interface{}) error {
config := &mapstructure.DecoderConfig{
Result: v,
TagName: "json",
WeaklyTypedInput: true,
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return err
}
err = decoder.Decode(data)
return err
}
func jsonEncode(data interface{}) (io.ReadWriter, error) {
var buf io.ReadWriter
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(data)
return buf, err
}
func joinURLs(basePath string, paths ...string) (*url.URL, error) {
u, err := url.Parse(basePath)
if err != nil {
return nil, fmt.Errorf("invalid url")
}
p2 := append([]string{u.Path}, paths...)
result := joinPreservingTrailingSlash(p2...)
u.Path = result
return u, nil
}
// JoinPreservingTrailingSlash does a path.Join of the specified elements,
// preserving any trailing slash on the last non-empty segment
// credit: https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/util/net/http.go#L40
func joinPreservingTrailingSlash(elem ...string) string {
// do the basic path join
result := path.Join(elem...)
// find the last non-empty segment
for i := len(elem) - 1; i >= 0; i-- {
if len(elem[i]) > 0 {
// if the last segment ended in a slash, ensure our result does as well
if strings.HasSuffix(elem[i], "/") && !strings.HasSuffix(result, "/") {
result += "/"
}
break
}
}
return result
}
func makeTimestamp() int64 {
return time.Now().UnixNano() / int64(time.Second)
}
func randomString(len int) string {
bytes := make([]byte, len)
for i := 0; i < len; i++ {
bytes[i] = byte(65 + rand.Intn(25)) //A=65 and Z = 65+25
}
return string(bytes)
}
// addOptions adds the parameters in opt as URL query parameters to s.
// opt must be a struct whose fields may contain "url" tags.
func addOptions(s string, opt interface{}) (string, error) {
v := reflect.ValueOf(opt)
if v.Kind() == reflect.Ptr && v.IsNil() {
return s, nil
}
u, err := url.Parse(s)
if err != nil {
return s, err
}
qs, err := query.Values(opt)
if err != nil {
return s, err
}
u.RawQuery = qs.Encode()
return u.String(), nil
}