-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathurl.go
232 lines (190 loc) · 4.64 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
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
package jsonapi
import (
"encoding/json"
"fmt"
"net/url"
"sort"
)
// NewURL builds a URL from a SimpleURL and a schema for validating and
// supplementing the object with extra information.
func NewURL(schema *Schema, su SimpleURL) (*URL, error) {
url := &URL{}
// Route
url.Route = su.Route
// Fragments
url.Fragments = su.Fragments
// IsCol, ResType, ResID, RelKind, Rel, BelongsToFilter
var (
typ Type
ok bool
)
if len(url.Fragments) == 0 {
return nil, NewErrBadRequest("Empty path", "There is no path.")
}
if len(url.Fragments) >= 1 {
if typ = schema.GetType(url.Fragments[0]); typ.Name == "" {
return nil, NewErrUnknownTypeInURL(url.Fragments[0])
}
if len(url.Fragments) == 1 {
url.IsCol = true
url.ResType = typ.Name
}
if len(url.Fragments) == 2 {
url.IsCol = false
url.ResType = typ.Name
url.ResID = url.Fragments[1]
}
}
if len(url.Fragments) >= 3 {
relName := url.Fragments[len(url.Fragments)-1]
if url.Rel, ok = typ.Rels[relName]; !ok {
return nil, NewErrUnknownRelationshipInPath(
typ.Name,
relName,
su.Path(),
)
}
url.IsCol = !url.Rel.ToOne
url.ResType = url.Rel.ToType
url.BelongsToFilter = BelongsToFilter{
Type: url.Fragments[0],
ID: url.Fragments[1],
Name: url.Rel.FromName,
ToName: url.Rel.ToName,
}
if len(url.Fragments) == 3 {
url.RelKind = "related"
} else if len(url.Fragments) == 4 {
url.RelKind = "self"
}
}
// Params
var err error
url.Params, err = NewParams(schema, su, url.ResType)
if err != nil {
return nil, err
}
return url, nil
}
// NewURLFromRaw parses rawurl to make a *url.URL before making and returning a
// *URL.
func NewURLFromRaw(schema *Schema, rawurl string) (*URL, error) {
url, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
su, err := NewSimpleURL(url)
if err != nil {
return nil, err
}
return NewURL(schema, su)
}
// A URL stores all the information from a URL formatted for a JSON:API request.
//
// The data structure allows to have more information than what the URL itself
// stores.
type URL struct {
// URL
Fragments []string // [users, u1, articles]
Route string // /users/:id/articles
// Data
IsCol bool
ResType string
ResID string
RelKind string
Rel Rel
BelongsToFilter BelongsToFilter
// Params
Params *Params
}
// String returns a string representation of the URL where special characters
// are escaped.
//
// The URL is normalized, so it always returns exactly the same string given the
// same URL.
func (u *URL) String() string {
// Path
path := "/"
for _, p := range u.Fragments {
path += p + "/"
}
path = path[:len(path)-1]
// Params
urlParams := []string{}
// Fields
fields := make([]string, 0, len(u.Params.Fields))
for key := range u.Params.Fields {
fields = append(fields, key)
}
sort.Strings(fields)
for _, typ := range fields {
sort.Strings(u.Params.Fields[typ])
param := "fields%5B" + typ + "%5D="
for _, f := range u.Params.Fields[typ] {
param += f + "%2C"
}
param = param[:len(param)-3]
urlParams = append(urlParams, param)
}
// Filter
if u.Params.Filter != nil {
mf, err := json.Marshal(u.Params.Filter)
if err != nil {
// This should not happen since Filter should be validated
// at this point.
panic(err)
}
param := "filter=" + string(mf)
urlParams = append(urlParams, param)
} else if u.Params.FilterLabel != "" {
urlParams = append(urlParams, "filter="+u.Params.FilterLabel)
}
// Pagination
if u.IsCol {
if num, ok := u.Params.Page["number"]; ok {
urlParams = append(
urlParams,
"page%5Bnumber%5D="+fmt.Sprint(num),
)
}
if size, ok := u.Params.Page["size"]; ok {
urlParams = append(
urlParams,
"page%5Bsize%5D="+fmt.Sprint(size),
)
}
}
// Sorting
if len(u.Params.SortingRules) > 0 {
param := "sort="
for _, attr := range u.Params.SortingRules {
param += attr + "%2C"
}
param = param[:len(param)-3]
urlParams = append(urlParams, param)
}
params := "?"
for _, param := range urlParams {
params += param + "&"
}
params = params[:len(params)-1]
return path + params
}
// UnescapedString returns the same thing as String, but special characters are
// not escaped.
func (u *URL) UnescapedString() string {
str, _ := url.PathUnescape(u.String())
// TODO Can an error occur?
return str
}
// A BelongsToFilter represents a parent resource, used to filter out resources
// that are not children of the parent.
//
// For example, in /articles/abc123/comments, the parent is the article with the
// ID abc123.
type BelongsToFilter struct {
Type string
ID string
Name string
ToName string
}