-
Notifications
You must be signed in to change notification settings - Fork 0
/
gt_null_url.go
375 lines (310 loc) · 9.61 KB
/
gt_null_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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package gt
import (
"database/sql/driver"
"encoding/json"
"net/url"
"path"
)
/*
Shortcut: parses successfully or panics. Should be used only in root scope. When
error handling is relevant, use `.Parse`.
*/
func ParseNullUrl(src string) (val NullUrl) {
try(val.Parse(src))
return
}
// Safe cast. Like `gt.NullUrl(*src)` but doesn't panic on nil pointer.
func ToNullUrl(src *url.URL) (val NullUrl) {
val.Set(src)
return
}
/*
Variant of `*url.URL` with a less-atrocious API.
Differences from `*url.URL`:
* Used by value, not by pointer.
* Full support for text, JSON, SQL encoding/decoding.
* Zero value is considered empty in text, and null in JSON and SQL.
* Easier to use.
* Fewer invalid states.
*/
type NullUrl url.URL
var (
_ = Encodable(NullUrl{})
_ = Decodable((*NullUrl)(nil))
)
// Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.
func (self NullUrl) IsZero() bool { return self == NullUrl{} }
// Implement `gt.Nullable`. True if zero.
func (self NullUrl) IsNull() bool { return self.IsZero() }
// Implement `gt.PtrGetter`, returning `*url.URL`.
func (self *NullUrl) GetPtr() any { return (*url.URL)(self) }
/*
Implement `gt.Getter`. If zero, returns `nil`, otherwise uses `.String` to
return a string representation.
*/
func (self NullUrl) Get() any {
if self.IsNull() {
return nil
}
return self.String()
}
// Implement `gt.Setter`, using `.Scan`. Panics on error.
func (self *NullUrl) Set(src any) { try(self.Scan(src)) }
// Implement `gt.Zeroer`, zeroing the receiver.
func (self *NullUrl) Zero() {
if self != nil {
*self = NullUrl{}
}
}
/*
Implement `fmt.Stringer`. If zero, returns an empty string. Otherwise formats
using `(*url.URL).String`.
*/
func (self NullUrl) String() string {
if self.IsNull() {
return ``
}
return self.Url().String()
}
/*
Implement `gt.Parser`. If the input is empty, zeroes the receiver. Otherwise
parses the input using `url.Parse`.
*/
func (self *NullUrl) Parse(src string) error {
if len(src) == 0 {
self.Zero()
return nil
}
val, err := url.Parse(src)
if err != nil {
return err
}
*self = NullUrl(*val)
return nil
}
// Implement `gt.AppenderTo`, using the same representation as `.String`.
func (self NullUrl) AppendTo(buf []byte) []byte {
if self.IsNull() {
return buf
}
return append(buf, self.String()...)
}
/*
Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the
same representation as `.String`.
*/
func (self NullUrl) MarshalText() ([]byte, error) {
if self.IsNull() {
return nil, nil
}
return self.AppendTo(nil), nil
}
// Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.
func (self *NullUrl) UnmarshalText(src []byte) error {
return self.Parse(bytesString(src))
}
/*
Implement `json.Marshaler`. If zero, returns bytes representing `null`.
Otherwise returns bytes representing a JSON string with the same text as in
`.String`.
*/
func (self NullUrl) MarshalJSON() ([]byte, error) {
if self.IsNull() {
return bytesNull, nil
}
return json.Marshal(self.String())
}
/*
Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`,
zeroes the receiver. Otherwise parses a JSON string, using the same algorithm
as `.Parse`.
*/
func (self *NullUrl) UnmarshalJSON(src []byte) error {
if isJsonEmpty(src) {
self.Zero()
return nil
}
if isJsonStr(src) {
return self.UnmarshalText(cutJsonStr(src))
}
return errJsonString(src, self)
}
// Implement `driver.Valuer`, using `.Get`.
func (self NullUrl) Value() (driver.Value, error) {
return self.Get(), nil
}
/*
Implement `sql.Scanner`, converting an arbitrary input to `gt.NullUrl` and
modifying the receiver. Acceptable inputs:
* `nil` -> use `.Zero`
* `string` -> use `.Parse`
* `[]byte` -> use `.UnmarshalText`
* `url.URL` -> convert and assign
* `*url.URL` -> use `.Zero` or convert and assign
* `NullUrl` -> assign
* `gt.Getter` -> scan underlying value
*/
func (self *NullUrl) Scan(src any) error {
switch src := src.(type) {
case nil:
self.Zero()
return nil
case string:
return self.Parse(src)
case []byte:
return self.UnmarshalText(src)
case url.URL:
*self = NullUrl(src)
return nil
case *url.URL:
if src == nil {
self.Zero()
} else {
*self = NullUrl(*src)
}
return nil
case NullUrl:
*self = src
return nil
default:
val, ok := get(src)
if ok {
return self.Scan(val)
}
return errScanType(self, src)
}
}
// Converts to `*url.URL`. The returned pointer refers to new memory.
func (self NullUrl) Url() *url.URL { return (*url.URL)(&self) }
// Free cast to `*url.URL`.
func (self *NullUrl) UrlPtr() *url.URL { return (*url.URL)(self) }
// If zero, returns nil. Otherwise returns a non-nil `*url.URL`.
func (self NullUrl) Maybe() *url.URL {
if self.IsNull() {
return nil
}
return self.Url()
}
/*
Returns a modified variant where `.Path` is replaced by combining the segments
via `gt.Join`. See the docs on `gt.Join`. Also see `.AddPath` that appends to
the path instead of replacing it.
*/
func (self NullUrl) WithPath(src ...string) NullUrl {
self.Path = ``
return self.AddPath(src...)
}
/*
Returns a modified variant where `.Path` is replaced by combining the existing
path with the segments via `gt.Join`. See the docs on `gt.Join`. Also see
`.WithPath` that replaces the path instead of appending.
*/
func (self NullUrl) AddPath(src ...string) NullUrl {
added := Join(src...)
if added == `` {
return self
}
if self.Host == `` {
// Suboptimal implementation. TODO tune.
self.Path = path.Join(self.Path, added)
return self
}
/**
This special case is supported to ensure consistency with equivalent URLs
decoded from strings, and reversibility between string-encoding and
string-decoding the resulting URL. When the host is not empty, if the path
does not begin with "/", string-encoding the URL automatically inserts
the "/" between the host and the path. The following URLs are distinct in
structure but equivalent in text:
Url{Host: `example.com`, Path: `one`} → `example.com/one`
Url{Host: `example.com`, Path: `/one`} → `example.com/one`
However, decoding such a URL from text generates only one of these
representations:
`example.com/one` → Url{Host: `example.com`, Path: `/one`}
This means the representation with the relative path is not reversible. This
has led to a production bug that broke authentication due to what may be
considered a bug in "net/http", where URLs with a non-empty host and a
relative path were rejected, causing a request error. To avoid such issues
and ensure reversible representation, we enforce a leading slash, ensuring
the same internal representation as what would be generated by parsing the
equivalent URL from text.
Suboptimal implementation. TODO tune.
*/
self.Path = path.Join(`/`, self.Path, added)
return self
}
// Returns a modified variant with replaced `.RawQuery`.
func (self NullUrl) WithRawQuery(val string) NullUrl {
self.RawQuery = val
return self
}
// Returns a modified variant with replaced `.RawQuery` encoded from input.
func (self NullUrl) WithQuery(val url.Values) NullUrl {
return self.WithRawQuery(val.Encode())
}
// Returns a modified variant with replaced `.Fragment`.
func (self NullUrl) WithFragment(val string) NullUrl {
self.Fragment = val
return self
}
// Implement `fmt.GoStringer`, returning valid Go code that constructs this value.
func (self NullUrl) GoString() string {
if self.IsNull() {
return `gt.NullUrl{}`
}
return "gt.ParseNullUrl(`" + self.String() + "`)"
}
// `gt.NullUrl` version of `(*url.URL).EscapedPath`.
func (self NullUrl) EscapedPath() string { return self.Url().EscapedPath() }
// `gt.NullUrl` version of `(*url.URL).EscapedFragment`.
func (self NullUrl) EscapedFragment() string { return self.Url().EscapedFragment() }
// `gt.NullUrl` version of `(*url.URL).Redacted`.
func (self NullUrl) Redacted() string { return self.Url().Redacted() }
// `gt.NullUrl` version of `(*url.URL).IsAbs`.
func (self NullUrl) IsAbs() bool { return self.Url().IsAbs() }
// `gt.NullUrl` version of `(*url.URL).Parse`.
func (self NullUrl) ParseIn(ref string) (NullUrl, error) {
val, err := self.Url().Parse(ref)
return ToNullUrl(val), err
}
// `gt.NullUrl` version of `(*url.URL).ResolveReference`.
func (self NullUrl) ResolveReference(ref NullUrl) NullUrl {
return ToNullUrl(self.Url().ResolveReference(ref.Url()))
}
// `gt.NullUrl` version of `(*url.URL).Query`.
func (self NullUrl) Query() url.Values { return self.Url().Query() }
// `gt.NullUrl` version of `(*url.URL).RequestURI`.
func (self NullUrl) RequestURI() string { return self.Url().RequestURI() }
// `gt.NullUrl` version of `(*url.URL).Hostname`.
func (self NullUrl) Hostname() string { return self.Url().Hostname() }
// `gt.NullUrl` version of `(*url.URL).Port`.
func (self NullUrl) Port() string { return self.Url().Port() }
/*
Like `path.Join` but with safeguards. Used internally by `gr.NullUrl.WithPath`,
exported because it may be useful separately. Differences from `path.Join`:
* More efficient if there's only 1 segment.
* Panics if any segment is "".
* Panics if any segment begins with ".." or "/..".
Combining segments of a URL path is usually done when building a URL for a
request. Accidentally calling the wrong endpoint can have consequences much
more annoying than a panic during request building.
*/
func Join(src ...string) string {
switch len(src) {
case 0:
return ``
case 1:
val := src[0]
noRelativeSegment(val)
noEmptySegment(val)
// We call this here for consistency with the default case,
// where `path.Join` automatically calls `path.Clean`.
return path.Clean(val)
default:
for _, val := range src {
noEmptySegment(val)
noRelativeSegment(val)
}
return path.Join(src...)
}
}