-
Notifications
You must be signed in to change notification settings - Fork 0
/
problems.go
317 lines (291 loc) · 8.14 KB
/
problems.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
// The problems package represents RFC7807 problem details.
package problems
import (
"encoding/json"
"encoding/xml"
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
)
const (
// ProblemMediaType is the default media type for a Problem response
ProblemMediaType = "application/problem+json"
)
type renderType string
var jsonType renderType = "json"
var xmlType renderType = "xml"
type Error interface {
error
Set(key string, value interface{}) Error
StatusCode() int
Get(string) interface{}
// ExtraFields lists the addon fields that can be retrieved with `Get`
ExtraFields() []string
}
// Problem is an RFC7807 representation of an error
type Problem struct {
// Type is a URI reference [RFC3986] that identifies the
// problem type. This specification encourages that, when
// dereferenced, it provide 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".
Type string `json:"type,omitempty"`
// Title is 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).
Title string `json:"title,omitempty"`
// Status is the HTTP status code ([RFC7231], Section 6)
// generated by the origin server for this occurrence of the problem.
Status int `json:"status,omitempty"`
// Detail is a human-readable explanation specific to this
// occurrence of the problem.
Detail string
// Instance is a URI reference that identifies the specific
// occurrence of the problem. It may or may not yield further
// information if dereferenced.
Instance string `json:"instance,omitempty"`
// Attributes are extra fields/data that can be added to the problem.
// They should be set with the `Set` method. The `Type` MUST be set
// and cannot be `about:blank`
Attributes map[string]interface{} `json:"vars,omitempty" xml:"vars,omitempty"`
err error
}
// Error returns a string representation of the problem to meet the Error interface definition
func (prob *Problem) Error() string {
return fmt.Sprintf("%d: %s", prob.Status, prob.Detail)
}
// Unwrap returns the underlying error or nil
func (prob *Problem) Unwrap() error {
return prob.err
}
// Set sets the extended attribute identified by key to value
// Setting anything other than the basic attributes requires a type other than `about:blank`
func (prob *Problem) Set(key string, value interface{}) error {
switch strings.Title(key) {
case "Subject":
fallthrough
case "Title":
prob.Title = fmt.Sprint(value)
case "Status":
return New(500, "Cannot set status with Set")
case "Type":
prob.Type = fmt.Sprint(value)
case "Message":
fallthrough
case "Detail":
prob.Detail = fmt.Sprint(value)
case "Instance":
prob.Instance = fmt.Sprint(value)
default:
if prob.Type == "" || prob.Type == "about:blank" {
err := FromError(prob)
err.Detail = fmt.Sprintf("Cannot set extended attribute (%s) unless Type is set", key)
err.PrettyPrint()
return err
}
if prob.Attributes == nil {
prob.Attributes = make(map[string]interface{})
}
prob.Attributes[key] = value
}
return nil
}
// Get allows retrieval of any of the fields.
func (prob *Problem) Get(key string) interface{} {
switch strings.Title(key) {
case "Subject":
fallthrough
case "Title":
return prob.Title
case "Status":
return prob.Status
case "Type":
return prob.Type
case "Message":
fallthrough
case "Detail":
return prob.Detail
case "Instance":
return prob.Instance
default:
if prob.Attributes == nil {
return ""
}
return prob.Attributes[key]
}
}
// Render will output the error as an HTTP response
func (prob *Problem) Render(w http.ResponseWriter, r *http.Request) error {
w.Header().Set("Content-Type", ProblemMediaType)
if prob.Status != 0 {
w.WriteHeader(prob.Status)
}
return json.NewEncoder(w).Encode(prob)
}
func (prob *Problem) MarshalJSON() ([]byte, error) {
return prob.Marshal(jsonType)
}
func (prob *Problem) MarshalXML() ([]byte, error) {
return prob.Marshal(xmlType)
}
func (prob *Problem) Marshal(renderAs renderType) ([]byte, error) {
out := make(map[string]interface{})
if prob.Type == "" {
prob.Type = "about:blank"
}
prob.Title = prob.GetTitle()
subjectValue := reflect.Indirect(reflect.ValueOf(prob))
subjectType := subjectValue.Type()
for i := 0; i < subjectType.NumField(); i++ {
field := subjectType.Field(i)
name := subjectType.Field(i).Name
if name != "Attributes" && name != "err" {
var key string
var ok bool
if key, ok = field.Tag.Lookup(string(renderAs)); !ok {
key = name
}
if strings.HasSuffix(key, "omitempty") {
if len(fmt.Sprintf("%v", subjectValue.FieldByName(name).Interface())) == 0 {
continue
}
}
key = strings.Split(key, ",")[0]
key = strings.ToLower(key)
out[key] = subjectValue.FieldByName(name).Interface()
}
}
if prob.err != nil && prob.Type != "about:blank" {
if problem, ok := prob.err.(*Problem); ok {
j, err := problem.MarshalJSON()
if err == nil {
out["error"] = j
}
}
out["error"] = prob.err.Error()
}
for k, v := range prob.Attributes {
out[strings.ToLower(k)] = v
}
switch renderAs {
case jsonType:
return json.Marshal(out)
case xmlType:
return xml.Marshal(out)
default:
return nil, New(500, "Invalid Marshal type specified")
}
}
func (prob *Problem) UnmarshalJSON(data []byte) error {
return prob.Unmarshal(jsonType, data)
}
func (prob *Problem) UnmarshalXML(data []byte) error {
return prob.Unmarshal(xmlType, data)
}
func (prob *Problem) Unmarshal(renderAs renderType, data []byte) error {
target := make(map[string]interface{})
switch renderAs {
case jsonType:
if err := json.Unmarshal(data, &target); err != nil {
return FromError(err)
}
case xmlType:
if err := xml.Unmarshal(data, &target); err != nil {
return FromError(err)
}
default:
return New(500, fmt.Sprintf("%s is an invalid type", renderAs))
}
prob.Attributes = make(map[string]interface{})
for k, v := range target {
switch strings.Title(k) {
case "Type":
prob.Type = fmt.Sprint(v)
case "Title":
prob.Title = fmt.Sprint(v)
case "Status":
stat, err := strconv.Atoi(fmt.Sprint(v))
if err != nil {
return FromError(err)
}
prob.Status = stat
case "Detail":
prob.Detail = fmt.Sprint(v)
case "Instance":
prob.Instance = fmt.Sprint(v)
default:
prob.Attributes[k] = v
}
}
return nil
}
func (prob *Problem) ExtraFields() []string {
var fields []string
for name := range prob.Attributes {
fields = append(fields, name)
}
return fields
}
// New initializes a problem
func New(status int, message string) *Problem {
err := Problem{}
err.Status = status
err.Detail = message
return &err
}
// Title returns the title of the problem or a default
func (p *Problem) GetTitle() string {
if len(p.Title) == 0 {
return http.StatusText(p.Status)
}
return p.Title
}
// FromErrorWithStatus creates a new problem from the
// provided error but sets the status to the one provided
// rather than the default of 500.
func FromErrorWithStatus(status int, err error) *Problem {
prob := Wrap(err)
if prob.Status != status {
prob.Status = status
}
return prob
}
// FromError creates a new problem from the provided error
func FromError(err error) *Problem {
return FromErrorWithStatus(http.StatusInternalServerError, err)
}
// Wrap creates a Problem that wraps a standard error
func Wrap(err error) *Problem {
if problem, ok := err.(*Problem); ok {
return problem
}
prob := New(500, err.Error())
prob.err = fmt.Errorf("%w", err)
return prob
}
func (prob *Problem) PrettyPrint() {
pp, err := json.MarshalIndent(prob, "", " ")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(pp))
}
// StatusCode returns the status of the problem
func (prob *Problem) StatusCode() int {
return prob.Status
}
// Errorf creates a problem from a formatted string
func Errorf(status int, format string, args ...interface{}) *Problem {
prob := New(status, fmt.Sprintf(format, args...))
for _, arg := range args {
if err, ok := arg.(error); ok {
prob.err = err
}
}
return prob
}