-
Notifications
You must be signed in to change notification settings - Fork 0
/
problemdetail.go
276 lines (226 loc) · 9.03 KB
/
problemdetail.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
package problemdetail
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"net/http"
"net/url"
)
// Error is an error type for ProblemDetail.
type Error string
// Error implements error interface.
func (e Error) Error() string { return string(e) }
// Set of errors for ProblemDetail.
const (
ErrTypeRequired = Error("type is required")
ErrTitleRequired = Error("title is required")
ErrStatusRequired = Error("status is required")
ErrDetailRequired = Error("detail is required")
ErrInstanceRequired = Error("instance is required")
ErrTypeFormat = Error("type is not a valid URI")
ErrInstanceFormat = Error("instance is not a valid URI")
)
// ProblemDetail is a problem detail as defined in RFC 7807.
// ref: https://tools.ietf.org/html/rfc7807
type ProblemDetail struct {
XMLName xml.Name `json:"-" xml:"urn:ietf:rfc:7807 problem"`
// Type is a URI reference [RFC3986] that identifies the problem type.
// This specification encourages that, when dereferenced, it provides human-readable documentation for the problem
// type (e.g., using HTML [W3C.REC-html5-20141028]). When this member is not present, its value is assumed to be
// "about:blank".
//
// ref: https://tools.ietf.org/html/rfc7807#section-3.1
Type string `json:"type" xml:"type"`
// Title A short, human-readable summary of the problem type. It SHOULD NOT change from occurrence to occurrence of
// the problem, except for purposes of localization (e.g., using proactive content negotiation; see [RFC7231],
// Section 3.4).
//
// ref: https://tools.ietf.org/html/rfc7807#section-3.1
Title string `json:"title" xml:"title"`
// Status The HTTP status code ([RFC7231], Section 6) generated by the origin server for this occurrence of the
// problem.
//
// ref: https://tools.ietf.org/html/rfc7807#section-3.1
Status int `json:"status" xml:"status"`
// Detail (optional) is a human-readable explanation specific to this occurrence of the problem.
//
// ref: https://tools.ietf.org/html/rfc7807#section-3.1
Detail string `json:"detail,omitempty" xml:"detail,omitempty"`
// Instance (optional) is a URI reference that identifies the specific occurrence of the problem.
// It may or may not yield further information if dereferenced.
//
// ref: https://tools.ietf.org/html/rfc7807#section-3.1
Instance string `json:"instance,omitempty" xml:"instance,omitempty"`
// flags is the level of validation to perform on the ProblemDetail.
flags validationLevel
}
// ProblemDetailer is contract for ProblemDetail, this interface is to make ProblemDetail extension possible by using
// struct embedding.
type ProblemDetailer interface {
error
// Kind returns the ProblemDetail.Type.
Kind() string
// Validate validates the problem detail based on the validation level. If the validation level is 0, no validation
// is performed. Default validation level is LStrict.
Validate() error
// WriteStatus writes the status code to ProblemDetail.Status. If ProblemDetail.Type is Untyped, ProblemDetail.Title
// will be updated with the status text. For example, if the status code is 404, the title will be "Not Found",
// which is the status text for 404 (http.StatusText(404)). Otherwise, the title will be left unchanged.
WriteStatus(code int)
}
// Option is the type for customizing the ProblemDetail.
type Option func(*ProblemDetail)
// Untyped is the default value for ProblemDetail.Type.
// When using this value, ProblemDetail.Title will be set to http.StatusText(code).
const Untyped = "about:blank"
// New creates a new ProblemDetail with the given type and options.
func New(typ string, opts ...Option) *ProblemDetail {
pd := ProblemDetail{
Type: typ,
flags: LStrict,
}
for _, opt := range opts {
opt(&pd)
}
return &pd
}
// Kind returns the ProblemDetail.Type.
func (p *ProblemDetail) Kind() string { return p.Type }
// Error implements error interface.
func (p *ProblemDetail) Error() string { return fmt.Sprintf("problem detail: %s", p.Type) }
// WriteStatus writes the status code to ProblemDetail.Status. If ProblemDetail.Type is Untyped, ProblemDetail.Title
// will be updated with the status text. For example, if the status code is 404, the title will be "Not Found",
// which is the status text for 404 (http.StatusText(404)). Otherwise, the title will be left unchanged.
func (p *ProblemDetail) WriteStatus(code int) {
p.Status = code
if p.Type == Untyped {
p.Title = http.StatusText(code)
}
}
// Validate validates the problem detail based on the validation level. If the validation level is 0, no validation
// is performed. Default validation level is LStrict.
func (p *ProblemDetail) Validate() error {
return errors.Join(
p.validateType(),
p.validateTitle(),
p.validateStatus(),
p.validateDetail(),
p.validateInstance(),
)
}
func (p *ProblemDetail) validateType() error {
if p.flags.has(LTypeRequired) && p.Type == "" {
return ErrTypeRequired
}
if p.flags.has(LTypeFormat) && p.Type != Untyped {
_, err := url.ParseRequestURI(p.Type)
if err != nil {
return errors.Join(ErrTypeFormat, err)
}
}
return nil
}
func (p *ProblemDetail) validateTitle() error {
if p.flags.has(LTitleRequired) && p.Title == "" {
return ErrTitleRequired
}
return nil
}
func (p *ProblemDetail) validateStatus() error {
if p.flags.has(LStatusRequired) && (p.Status <= 0 || p.Status >= 600) {
return ErrStatusRequired
}
return nil
}
func (p *ProblemDetail) validateDetail() error {
if p.flags.has(LDetailRequired) && p.Detail == "" {
return ErrDetailRequired
}
return nil
}
func (p *ProblemDetail) validateInstance() error {
if p.flags.has(LInstanceRequired) && p.Instance == "" {
return ErrInstanceRequired
}
if p.flags.has(LInstanceFormat) && p.Instance != "" {
_, err := url.Parse(p.Instance) // since instance is relative URI.
if err != nil {
return errors.Join(ErrInstanceFormat, err)
}
}
return nil
}
// validationLevel is bitfield for validation level.
type validationLevel uint8
const (
// LTypeRequired is to ensure that ProblemDetail.Type is not empty.
LTypeRequired validationLevel = 1 << iota
// LTitleRequired is to ensure that ProblemDetail.Title is not empty.
LTitleRequired
// LStatusRequired is to ensure that ProblemDetail.Status is not empty.
LStatusRequired
// LDetailRequired is to ensure that ProblemDetail.Detail is not empty.
LDetailRequired
// LInstanceRequired is to ensure that ProblemDetail.Instance is not empty.
LInstanceRequired
// LTypeFormat is to ensure that ProblemDetail.Type is a valid URI.
LTypeFormat
// LInstanceFormat is to ensure that ProblemDetail.Instance is a valid URI.
LInstanceFormat
// LStandard is the standard validation level based on RFC 7807.
LStandard = LTypeRequired | LTitleRequired | LStatusRequired
// LAllRequired is to ensure that all fields are not empty.
LAllRequired = LStandard | LDetailRequired | LInstanceRequired
// LStrict is to ensure that all fields are not empty and all URIs are valid.
LStrict = LAllRequired | LTypeFormat | LInstanceFormat
)
// has returns true if the flag has the given flag.
func (l validationLevel) has(flag validationLevel) bool { return l&flag != 0 }
// WithValidateLevel sets the validation level of the ProblemDetail.
func WithValidateLevel(level validationLevel) Option {
return func(pd *ProblemDetail) { pd.flags = level }
}
// WithTitle sets the title of the ProblemDetail.
func WithTitle(title string) Option {
return func(pd *ProblemDetail) { pd.Title = title }
}
// WithDetail sets the detail of the ProblemDetail.
func WithDetail(detail string) Option {
return func(pd *ProblemDetail) { pd.Detail = detail }
}
// WithInstance sets the instance of the ProblemDetail.
func WithInstance(instance string) Option {
return func(pd *ProblemDetail) { pd.Instance = instance }
}
// WriteJSON writes the problem detail to the response writer as JSON.
// The content type is set to application/problem+json; charset=utf-8.
// The status code will be set to both ProblemDetail.Status and http.ResponseWriter.
//
// If the problem detail is invalid, an error is returned.
func WriteJSON(w http.ResponseWriter, pd ProblemDetailer, code int) error {
pd.WriteStatus(code)
if err := pd.Validate(); err != nil {
return fmt.Errorf("WriteJSON: %w", err)
}
writeContentTypeAndStatus(w, "application/problem+json; charset=utf-8", code)
return json.NewEncoder(w).Encode(pd)
}
// WriteXML writes the problem detail to the response writer as XML.
// The content type is set to application/problem+xml; charset=utf-8.
// The status code will be set to both ProblemDetail.Status and http.ResponseWriter.
//
// If the problem detail is invalid, an error is returned.
func WriteXML(w http.ResponseWriter, pd ProblemDetailer, code int) error {
pd.WriteStatus(code)
if err := pd.Validate(); err != nil {
return fmt.Errorf("WriteXML: %w", err)
}
writeContentTypeAndStatus(w, "application/problem+xml; charset=utf-8", code)
return xml.NewEncoder(w).Encode(pd)
}
// writeContentTypeAndStatus writes the content type and status code to the response writer.
func writeContentTypeAndStatus(w http.ResponseWriter, value string, code int) {
w.Header().Add("Content-Type", value)
w.WriteHeader(code)
}