-
Notifications
You must be signed in to change notification settings - Fork 0
/
url.go
104 lines (84 loc) · 1.92 KB
/
url.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
package goutil
import (
"encoding/json"
"fmt"
"log"
"net/url"
"strings"
)
// URL wraps a url string with its GET parameters
type URL struct {
URL string
GetParameters map[string]interface{}
}
// NewURL instanciates
func NewURL(url string) *URL {
return &URL{
URL: url,
GetParameters: map[string]interface{}{},
}
}
// URLJoin takes a bunch of urls and concatenate them
func URLJoin(ss ...string) *URL {
parts := []string{}
for _, s := range ss {
// Skip empty strings
if s == "" {
continue
}
// Concatenate properly
parts = append(parts, urlJoinRemoveExtremeSlashes(s))
}
return NewURL(strings.Join(parts, "/"))
}
// SetURLParameter sets one parameters
func (u *URL) SetURLJSONParameter(key string, value interface{}) *URL {
b, err := json.Marshal(value)
if err != nil {
log.Fatalf("%v", Pretty(err))
}
u.GetParameters[key] = string(b)
return u
}
// SetURLParameter sets one parameters
func (u *URL) SetURLParameter(key string, value interface{}) *URL {
u.GetParameters[key] = value
return u
}
// SetURLParameters sets one parameters
func (u *URL) SetURLParameters(params map[string]interface{}) *URL {
for key, value := range params {
u.GetParameters[key] = value
}
return u
}
// Format creates the complete URL
func (u *URL) Format() string {
_u, err := url.Parse(u.URL)
if err != nil {
log.Fatalf("%s", Pretty(err))
}
q := _u.Query()
for key, value := range u.GetParameters {
q.Set(key, fmt.Sprintf("%v", DefaultIfNull(value, "")))
}
_u.RawQuery = q.Encode()
return _u.String()
}
// urlJoinRemoveExtremeSlashes removes first and last slash of a URL part
// useful for joining chunks to make a complete URL
func urlJoinRemoveExtremeSlashes(s string) string {
if s == "" {
return s
}
firstLetter := s[:1]
lastLetter := s[(len(s) - 1):]
newS := s
if firstLetter == "/" {
newS = newS[1:]
}
if lastLetter == "/" {
newS = newS[:(len(newS) - 1)]
}
return newS
}