-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent.go
More file actions
88 lines (76 loc) · 1.97 KB
/
Copy pathcomponent.go
File metadata and controls
88 lines (76 loc) · 1.97 KB
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
package begger
import (
"fmt"
"net/url"
"strings"
)
type RequestComponents struct {
Url Url
HTTPMethod string
Body []byte
Headers Headers
}
/*
Provide either of `Actual` or `Components`. If both of these are provided,
`Actual` gets priority.
*/
type Url struct {
/*
Full URL containing host, port (if not default), path parameters' actual
values and query string.
*/
Actual *string
Components *UrlComponents
}
func (u *Url) Get() string {
if u.Actual != nil {
return *u.Actual
} else if u.Components != nil {
return u.Components.GetUrl()
}
panic("Either the full url or the url parts must be supplied.")
}
type UrlComponents struct {
Host string
Port *int
PathFormat string
PathParams PathParams
QueryParams QueryParams
}
func (u *UrlComponents) GetUrl() string {
url := strings.TrimRight(u.Host, "/")
if u.Port != nil && *u.Port > 0 {
url += fmt.Sprintf(":%d", *u.Port)
}
url += u.PathParams.ActualPath(u.PathFormat)
if qs := u.QueryParams.ToEncodedString(); qs != "" {
url += "?" + qs
}
return url
}
type QueryParams map[string]string
func (q *QueryParams) ToEncodedString() string {
params := url.Values{}
for key, val := range *q {
params.Add(key, val)
}
return params.Encode()
}
type PathParams map[string]string
/*
Make sure to use the path param's placeholder structure as the map key.
For example,
- If pathFormat uses {id}, then it must be PathParams{"{id}": 123}
- If pathFormat uses :id, then it must be PathParams{":id": 123}
** NOTE: This method will make sure that the actual path will contain
a leading slash (/). For example, if the pathFormat is either "users/:id"
or "/users/:id", the return value will always be like "/users/123".
*/
func (p *PathParams) ActualPath(pathFormat string) string {
var oldNew []string
for key, val := range *p {
oldNew = append(oldNew, key, val)
}
return "/" + strings.NewReplacer(oldNew...).Replace(strings.TrimLeft(pathFormat, "/"))
}
type Headers map[string]string