-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathcore_url.go
94 lines (81 loc) · 1.71 KB
/
core_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
package requests
import (
"cmp"
"net/url"
"slices"
)
type multimap struct {
key string
values []string
optional bool
}
type kvpair struct {
key, value string
}
type urlBuilder struct {
baseurl string
scheme, host string
paths []string
params []multimap
}
func (ub *urlBuilder) BaseURL(baseurl string) {
ub.baseurl = baseurl
}
func (ub *urlBuilder) Scheme(scheme string) {
ub.scheme = scheme
}
func (ub *urlBuilder) Host(host string) {
ub.host = host
}
func (ub *urlBuilder) Path(path string) {
ub.paths = append(ub.paths, path)
}
func (ub *urlBuilder) Param(key string, values ...string) {
ub.params = append(ub.params, multimap{key, values, false})
}
func (ub *urlBuilder) ParamOptional(key string, values ...string) {
ub.params = append(ub.params, multimap{key, values, true})
}
func (ub *urlBuilder) Clone() *urlBuilder {
ub2 := *ub
ub2.paths = slices.Clip(ub2.paths)
ub2.params = slices.Clip(ub2.params)
return &ub2
}
func (ub *urlBuilder) URL() (u *url.URL, err error) {
u, err = url.Parse(ub.baseurl)
if err != nil {
return new(url.URL), err
}
u.Scheme = cmp.Or(
ub.scheme,
u.Scheme,
"https",
)
u.Host = cmp.Or(ub.host, u.Host)
for _, p := range ub.paths {
u.Path = u.ResolveReference(&url.URL{Path: p}).Path
}
if len(ub.params) > 0 {
q := u.Query()
for _, kv := range ub.params {
if !kv.optional {
q[kv.key] = kv.values
}
}
for _, kv := range ub.params {
if kv.optional &&
q.Get(kv.key) == "" &&
cmp.Or(kv.values...) != "" {
q[kv.key] = kv.values
}
}
u.RawQuery = q.Encode()
}
// Reparsing, in case the path rewriting broke the URL
u, err = url.Parse(u.String())
if err != nil {
return new(url.URL), err
}
return u, nil
}