-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem.go
More file actions
494 lines (414 loc) · 13.5 KB
/
problem.go
File metadata and controls
494 lines (414 loc) · 13.5 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
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// Package problem implements the RFC 9457 problem details specification in Go.
//
// It also provides some functionality for directly responding to HTTP requests with problems
// and for defining reusable problem types.
package problem
import (
"cmp"
"errors"
"maps"
"net/http"
"strings"
"github.com/go-json-experiment/json"
"github.com/go-json-experiment/json/jsontext"
)
const (
// AboutBlankTypeURI is the default problem type and is equivalent to not specifying a problem type.
//
// See also https://datatracker.ietf.org/doc/html/rfc9457#name-aboutblank
AboutBlankTypeURI = "about:blank"
)
const (
// ContentType is the media type used for problem responses, as defined by IANA.
//
// See also https://datatracker.ietf.org/doc/html/rfc9457#name-iana-considerations
ContentType = "application/problem+json"
)
// Details defines an RFC 9457 problem details object.
//
// Details also implements the [error] interface and can optionally wrap an existing [error] value.
type Details struct {
// Type contains the problem type as a URI.
//
// If empty, this is the same as "about:blank". See [AboutBlankTypeURI] for more information.
//
// See also https://datatracker.ietf.org/doc/html/rfc9457#name-type
Type string
// Status is indicating the HTTP status code generated for this occurrence of the problem.
//
// This should be the same code as used for the HTTP response and is only advisory.
//
// See also https://datatracker.ietf.org/doc/html/rfc9457#name-status
Status int
// Title is string containing a short, human-readable summary of the problem type
//
// See also https://datatracker.ietf.org/doc/html/rfc9457#name-title
Title string
// Detail is string containing a human-readable explanation specific to this occurrence of the problem.
//
// See also https://datatracker.ietf.org/doc/html/rfc9457#name-detail
Detail string
// Instance is string containing a URI reference that identifies the specific occurrence of the problem
//
// See also https://datatracker.ietf.org/doc/html/rfc9457#name-instance
Instance string
// Extensions contains any extensions that should be added to the response.
//
// If the problem was parsed from a JSON response this will include all extension fields.
//
// See also https://datatracker.ietf.org/doc/html/rfc9457#name-extension-members
Extensions map[string]any
// Underlying optionally contains the underlying error that lead to / is described by this problem.
//
// This field is not part of RFC 9457 and is neither included in generated JSON nor populated during unmarshaling.
Underlying error
}
// Option defines functional options that can be used to fill in optional values when creating a [Details] via
// [New] or via [Type.Details].
type Option func(*Details)
// WithStatus sets the Status for a new Details value.
func WithStatus(status int) Option {
return func(d *Details) {
d.Status = status
}
}
// WithDetail sets the Detail for a new Details value.
func WithDetail(detail string) Option {
return func(d *Details) {
d.Detail = detail
}
}
// WithInstance sets the Instance for a new Details value.
func WithInstance(instance string) Option {
return func(d *Details) {
d.Instance = instance
}
}
// WithExtension adds the given key-value pair to the Extensions of a new Details value.
func WithExtension(key string, value any) Option {
return func(d *Details) {
if d.Extensions == nil {
d.Extensions = make(map[string]any)
}
d.Extensions[key] = value
}
}
// WithExtensions adds the values to the Extensions of a new Details value.
func WithExtensions(extensions map[string]any) Option {
return func(d *Details) {
if d.Extensions == nil {
d.Extensions = make(map[string]any, len(extensions))
}
maps.Copy(d.Extensions, extensions)
}
}
// WithUnderlying sets the given value as the underlying error of a new Details value.
func WithUnderlying(err error) Option {
return func(d *Details) {
d.Underlying = err
}
}
// New returns a new Details instance using the given type, status and title.
//
// It is also possible to set the Detail and Instance fields as well as extensions by
// providing one or more [Option] values.
//
// Most users should prefer creating a Details instance via a struct literal or using [Type.Details] instead.
func New(typ string, title string, status int, opts ...Option) *Details {
p := &Details{
Type: typ,
Status: status,
Title: title,
}
for _, opt := range opts {
opt(p)
}
return p
}
// From returns the problem returned as part of the given HTTP response if any.
//
// As a special case, if [Details.Status] would be 0, it will instead be set to the response status code.
//
// The response body will be closed automatically.
//
// If the response is not of type application/problem+json, the function returns nil, nil and does not close the body.
func From(resp *http.Response) (*Details, error) {
ct := resp.Header.Get("Content-Type")
if !isContentType(ContentType, ct) {
return nil, nil
}
defer func() {
_ = resp.Body.Close()
}()
var d Details
if err := json.UnmarshalRead(resp.Body, &d); err != nil {
return nil, err
}
if d.Status == 0 {
d.Status = resp.StatusCode
}
return &d, nil
}
func isContentType(expected, actual string) bool {
if !strings.HasPrefix(actual, expected) {
return false
}
return actual == expected || actual[len(expected)] == ';'
}
var _ error = (*Details)(nil)
// Error implements the error interface. The returned value is the same as d.Title.
func (d *Details) Error() string {
return d.Title
}
// Unwrap implements the interface used functions like [errors.Is] and [errors.As] to get the underlying error, if any.
func (d *Details) Unwrap() error {
return d.Underlying
}
// MarshalJSON implements the json.Marshaler interface.
//
// See MarshalJSONTo for details.
func (d *Details) MarshalJSON() ([]byte, error) {
// This will call (*Details).MarshalJSONTo.
return json.Marshal(d)
}
var _ json.MarshalerTo = (*Details)(nil)
// MarshalJSONTo implements the json.MarshalerTo interface.
//
// If no Type is set, "about:blank" is used. See also [AboutBlankTypeURI].
//
// Extension fields named "type", "status", "title", "detail" or "instance" are ignored when marshaling in favor
// of the respective struct fields even if the field is empty.
func (d *Details) MarshalJSONTo(enc *jsontext.Encoder) error {
// We implement marshalling ourselves so that we can put the defined fields and the extensions
// into a single JSON object.
//
// As a nice benefit this is also faster than using the default, reflection-based approach.
if err := enc.WriteToken(jsontext.BeginObject); err != nil {
return err
}
typ := cmp.Or(d.Type, AboutBlankTypeURI)
if d.Type != "" {
if err := enc.WriteToken(jsontext.String("type")); err != nil {
return err
}
if err := enc.WriteToken(jsontext.String(typ)); err != nil {
return err
}
}
if d.Status != 0 {
if err := enc.WriteToken(jsontext.String("status")); err != nil {
return err
}
if err := enc.WriteToken(jsontext.Int(int64(d.Status))); err != nil {
return err
}
}
if d.Title != "" {
if err := enc.WriteToken(jsontext.String("title")); err != nil {
return err
}
if err := enc.WriteToken(jsontext.String(d.Title)); err != nil {
return err
}
}
if d.Detail != "" {
if err := enc.WriteToken(jsontext.String("detail")); err != nil {
return err
}
if err := enc.WriteToken(jsontext.String(d.Detail)); err != nil {
return err
}
}
if d.Instance != "" {
if err := enc.WriteToken(jsontext.String("instance")); err != nil {
return err
}
if err := enc.WriteToken(jsontext.String(d.Instance)); err != nil {
return err
}
}
for k, v := range d.Extensions {
if k == "type" || k == "status" || k == "title" || k == "detail" || k == "instance" {
continue
}
if err := enc.WriteToken(jsontext.String(k)); err != nil {
return err
}
if err := json.MarshalEncode(enc, v); err != nil {
return err
}
}
if err := enc.WriteToken(jsontext.EndObject); err != nil {
return err
}
return nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
//
// See UnmarshalJSONV2 for details.
func (d *Details) UnmarshalJSON(b []byte) error {
// This will call (*Details).UnmarshalJSONV2.
return json.Unmarshal(b, d)
}
var _ json.UnmarshalerFrom = (*Details)(nil)
// UnmarshalJSONFrom implements the json.UnmarshalerFrom interface.
//
// As required by RFC 9457 UnmarshalJSONV2 will ignore values for known fields if those values have the wrong type.
//
// For example if the parsed JSON contains a field "status" with the code "400" as a JSON string, the field will be
// ignored even if it may be possible to parse it as an integer.
func (d *Details) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
var m map[string]any
if err := json.UnmarshalDecode(dec, &m); err != nil {
return err
}
// 3.1. Members of a Problem Details Object
//
// Problem detail objects can have the following members. If a member's
// value type does not match the specified type, the member MUST be
// ignored -- i.e., processing will continue as if the member had not
// been present.
//
// https://datatracker.ietf.org/doc/html/rfc9457#name-members-of-a-problem-detail
if v, ok := m["type"].(string); ok {
d.Type = v
}
if v, ok := m["status"].(float64); ok && float64(int(v)) == v {
d.Status = int(v)
}
if v, ok := m["title"].(string); ok {
d.Title = v
}
if v, ok := m["detail"].(string); ok {
d.Detail = v
}
if v, ok := m["instance"].(string); ok {
d.Instance = v
}
delete(m, "type")
delete(m, "status")
delete(m, "title")
delete(m, "detail")
delete(m, "instance")
if len(m) != 0 {
d.Extensions = m
}
return nil
}
// ServeHTTP encodes the value as JSON and writes it to the given response writer.
//
// If encoding fails, no data will be written and ServeHTTP will panic.
//
// ServeHTTP deletes any existing Content-Length header, sets Content-Type to “application/problem+json”, and sets
// X-Content-Type-Options to “nosniff”.
//
// If set the Status field is used to set the HTTP status. Otherwise [http.StatusInternalServerError] is used.
//
// ServeHTTP implements the [http.Handler] interface.
func (d *Details) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
b, err := json.Marshal(d)
if err != nil {
// If we get an error here we consider this a bug and panic.
panic(err)
}
// Remove the Content-Length header and set X-Content-Type-Options as done by [http.Error].
h := w.Header()
h.Del("Content-Length")
h.Set("Content-Type", ContentType)
h.Set("X-Content-Type-Options", "nosniff")
if d.Status != 0 {
w.WriteHeader(d.Status)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
_, _ = w.Write(b)
}
// Type defines a specific problem type that can be used to create new Details instances.
//
// The main use case is as package-level variables that can than be used across different types and functions. These
// types can reduce boilerplate and serve as part of the documentation.
//
// Example:
//
// var OutOfCreditProblemType = &problem.Type{
// URI: "https://example.com/probs/out-of-credit",
// Title: "You do not have enough credit.",
// Status: http.StatusForbidden,
// }
//
// Than in a handler:
//
// type (s *MyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// // ...
// if outOfCredit {
// OutOfCreditProblemType.Details().ServeHTTP(w, r)
// return
// }
// // ...
// }
//
// When available, extra information can be added using [Option]s:
//
// if outOfCredit {
// OutOfCreditProblemType.Details(
// problem.WithDetail("Your current balance is 30, but that costs 50."),
// problem.WithInstance("/account/12345/msgs/abc"),
// problem.WithExtension("balance", 30),
// problem.WithExtension("accounts", []string{"/account/12345", "/account/67890"}),
// ).ServeHTTP(w, r)
// return
// }
type Type struct {
// URI defines the type URI (typically, with the "http" or "https" scheme)
URI string
// Title contains a short, human-readable summary of the problem type.
Title string
// Status is the HTTP status code that should be used for responses.
Status int
// Extensions contains fixed extensions that are automatically added to Details instances
// created from this type.
Extensions map[string]any
}
// Is returns true if the given error can be converted to a [*Details] using [errors.As] and the URI, Title and Status
// match the given type.
//
// If any of [Type.URI], [Type.Title] or [Type.Status] is empty / zero, the field is skipped.
//
// For example, for a type with only a URI and no title or status, only the URI will be compared.
func Is(err error, t *Type) bool {
var d *Details
if !errors.As(err, &d) {
return false
}
switch {
case t.URI != "" && t.URI != cmp.Or(d.Type, AboutBlankTypeURI):
return false
case t.Title != "" && t.Title != d.Title:
return false
case t.Status != 0 && t.Status != d.Status:
return false
default:
return true
}
}
// Details creates a new [Details] instance from this type.
//
// It is equivalent to calling New(p.URI, p.Status, p.Title, opts...).
func (t *Type) Details(opts ...Option) *Details {
d := New(t.URI, t.Title, t.Status)
// Note: Conceptually what we want is to pass our extensions to New via WithExtensions as
// the first option, so that later options can override any values that come from the type,
//
// Unfortunately doing this is kinda verbose and, more importantly, forces an allocation,
// which we want to avoid.
//
// So, instead we handle the options ourselves instead of passing them to New and set the
// extensions manually before applying the options.
if len(t.Extensions) > 0 {
d.Extensions = maps.Clone(t.Extensions)
}
for _, opt := range opts {
opt(d)
}
return d
}