-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjsonapi.go
86 lines (71 loc) · 2.58 KB
/
jsonapi.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
package josh
// JSON:API resource object type.
//
// Should be used as the Data attribute for [Resp] if you want your API
// to follow the JSON:API spec.
//
// https://jsonapi.org/format/#document-resource-objects
type Data[T any] struct {
ID string `json:"id"`
Type string `json:"type"`
Attributes T `json:"attributes,omitempty"`
Links any `json:"links,omitempty"`
Meta any `json:"meta,omitempty"`
Relationships any `json:"relationships,omitempty"`
}
// An error response. The structure follows the JSON:API spec.
//
// https://jsonapi.org/format/#error-objects
type Error struct {
// ID is a unique identifier for this particular occurrence of a problem.
ID string `json:"id,omitempty"`
// Title is a short, human-readable summary of the problem.
//
// It SHOULD NOT change from occurrence to occurrence of the problem,
// except for purposes of localization.
Title string `json:"title,omitempty"`
// Detail is a human-readable explanation specific to this occurrence of the problem.
//
// Like title, this field's value can be localized.
Detail string `json:"detail,omitempty"`
// Status is the HTTP status code applicable to this problem, expressed as a string value.
Status string `json:"status,omitempty"`
// Code is an application-specific error code, expressed as a string value.
Code string `json:"code,omitempty"`
// Source is a reference to the primary source of the error.
//
// Constructed with either [SourcePointer], [SourceParameter], or [SourceHeader].
Source *source `json:"source,omitempty"`
// Meta is an object containing non-standard meta-information about the error.
Meta any `json:"meta,omitempty"`
}
func (err *Error) Error() string {
if err == nil {
return ""
}
prefix := ""
if err.Title != "" {
prefix = err.Title + ": "
}
return prefix + err.Detail
}
type source struct {
// A JSON Pointer (RFC6901) to the value in the request document that caused the error.
Pointer string `json:"pointer,omitempty"`
// Which URI query parameter caused the error.
Parameter string `json:"parameter,omitempty"`
// The name of a single request header which caused the error.
Header string `json:"header,omitempty"`
}
// A JSON Pointer (RFC6901) to the value in the request document that caused the error.
func SourcePointer(v string) *source {
return &source{Pointer: v}
}
// Which URI query parameter caused the error.
func SourceParameter(v string) *source {
return &source{Parameter: v}
}
// The name of a single request header which caused the error.
func SourceHeader(v string) *source {
return &source{Header: v}
}