-
Notifications
You must be signed in to change notification settings - Fork 3
/
problem.go
269 lines (234 loc) · 7.59 KB
/
problem.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
package problem
import (
"encoding/json"
"encoding/xml"
"fmt"
"net/http"
"strconv"
)
const (
// ContentTypeJSON https://tools.ietf.org/html/rfc7807#section-6.1
ContentTypeJSON = "application/problem+json"
// ContentTypeXML https://tools.ietf.org/html/rfc7807#section-6.2
ContentTypeXML = "application/problem+xml"
)
// An Option configures a Problem using the functional options paradigm
// popularized by Rob Pike.
type Option interface {
apply(*Problem)
}
type optionFunc func(*Problem)
func (f optionFunc) apply(problem *Problem) { f(problem) }
// Problem is an RFC7807 error and can be compared with errors.Is()
type Problem struct {
data map[string]interface{}
reason error
}
// JSON returns the Problem as json bytes
func (p Problem) JSON() []byte {
b, _ := p.MarshalJSON()
return b
}
// XML returns the Problem as json bytes
func (p Problem) XML() []byte {
b, _ := xml.Marshal(p)
return b
}
// UnmarshalJSON implements the json.Unmarshaler interface
func (p Problem) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, &p.data)
}
// MarshalJSON implements the json.Marshaler interface
func (p Problem) MarshalJSON() ([]byte, error) {
return json.Marshal(&p.data)
}
// UnmarshalXML implements the xml.Unmarshaler interface
func (p *Problem) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
lastElem := ""
for {
if tok, err := d.Token(); err == nil {
switch t := tok.(type) {
case xml.StartElement:
if t.Name.Space != "urn:ietf:rfc:7807" {
return fmt.Errorf("Expected namespace urn:ietf:rfc:7807")
}
lastElem = t.Name.Local
case xml.CharData:
if lastElem != "" {
if lastElem == "status" {
i, err := strconv.Atoi(string(t))
if err != nil {
return err
}
p = p.Append(Status(i))
} else {
p = p.Append(Custom(lastElem, string(t)))
}
}
}
} else {
break
}
}
return nil
}
// MarshalXML implements the xml.Marshaler interface
func (p Problem) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
start.Name = xml.Name{Local: "problem"}
start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "xmlns"}, Value: "urn:ietf:rfc:7807"})
tokens := []xml.Token{start}
for k, v := range p.data {
v := fmt.Sprintf("%v", v)
t := xml.StartElement{Name: xml.Name{Space: "", Local: k}}
tokens = append(tokens, t, xml.CharData(v), xml.EndElement{Name: t.Name})
}
tokens = append(tokens, xml.EndElement{Name: start.Name})
for _, t := range tokens {
e.EncodeToken(t)
}
return e.Flush()
}
// XMLString returns the Problem as xml
func (p Problem) XMLString() string {
return string(p.XML())
}
// JSONString returns the Problem as json string
func (p Problem) JSONString() string {
return string(p.JSON())
}
// Error implements the error interface, so a Problem can be used as an error
func (p Problem) Error() string {
return p.JSONString()
}
// Is compares Problem.Error() with err.Error()
func (p Problem) Is(err error) bool {
return p.Error() == err.Error()
}
// Unwrap returns the result of calling the Unwrap method on err, if err implements Unwrap.
// Otherwise, Unwrap returns nil.
func (p Problem) Unwrap() error {
return p.reason
}
// WriteHeaderTo writes the HTTP headers for the JSON Problem ContentType and the
// problem's HTTP statuscode. This is suitable for responding to HEAD requests.
func (p Problem) WriteHeaderTo(w http.ResponseWriter) {
w.Header().Set("Content-Type", ContentTypeJSON)
if statuscode, ok := p.data["status"]; ok {
if statusint, ok := statuscode.(int); ok {
w.WriteHeader(statusint)
}
}
}
// WriteTo writes the JSON Problem to an HTTP Response Writer using the correct
// Content-Type and the problem's HTTP statuscode
func (p Problem) WriteTo(w http.ResponseWriter) (int, error) {
p.WriteHeaderTo(w)
return w.Write(p.JSON())
}
// WriteXMLHeaderTo writes the HTTP headers for the XML Problem ContentType and the
// problem's HTTP statuscode. This is suitable for responding to HEAD requests.
func (p Problem) WriteXMLHeaderTo(w http.ResponseWriter) {
w.Header().Set("Content-Type", ContentTypeXML)
if statuscode, ok := p.data["status"]; ok {
if statusint, ok := statuscode.(int); ok {
w.WriteHeader(statusint)
}
}
}
// WriteXMLTo writes the XML Problem to an HTTP Response Writer using the correct
// Content-Type and the problem's HTTP statuscode
func (p Problem) WriteXMLTo(w http.ResponseWriter) (int, error) {
p.WriteXMLHeaderTo(w)
return w.Write(p.XML())
}
// New generates a new Problem
func New(opts ...Option) *Problem {
problem := &Problem{}
problem.data = make(map[string]interface{})
for _, opt := range opts {
opt.apply(problem)
}
return problem
}
// Of creates a Problem based on StatusCode with Title automatically set
func Of(statusCode int) *Problem {
return New(Status(statusCode), Title(http.StatusText(statusCode)))
}
// Append an Option to a existing Problem
func (p *Problem) Append(opts ...Option) *Problem {
for _, opt := range opts {
opt.apply(p)
}
return p
}
// Wrap an error to the Problem
func Wrap(err error) Option {
return optionFunc(func(problem *Problem) {
problem.reason = err
problem.data["reason"] = err.Error()
})
}
// WrapSilent wraps an error inside of the Problem without placing the wrapped
// error into the problem's JSON body. Useful for cases where the underlying
// error needs to be preserved but not transmitted to the user.
func WrapSilent(err error) Option {
return optionFunc(func(problem *Problem) {
problem.reason = err
})
}
// Type sets the type URI (typically, with the "http" or "https" scheme) that identifies the problem type.
// When dereferenced, it SHOULD provide human-readable documentation for the problem type
func Type(uri string) Option {
return optionFunc(func(problem *Problem) {
problem.data["type"] = uri
})
}
// Title sets a title that appropriately describes it (think short)
// Written in english and readable for engineers (usually not suited for
// non technical stakeholders and not localized); example: Service Unavailable
func Title(title string) Option {
return optionFunc(func(problem *Problem) {
problem.data["title"] = title
})
}
// Titlef sets a title using a format string that appropriately describes it (think short)
// Written in english and readable for engineers (usually not suited for
// non technical stakeholders and not localized); example: Service Unavailable
func Titlef(format string, values ...interface{}) Option {
return Title(fmt.Sprintf(format, values...))
}
// Status sets the HTTP status code generated by the origin server for this
// occurrence of the problem.
func Status(status int) Option {
return optionFunc(func(problem *Problem) {
problem.data["status"] = status
})
}
// Detail A human readable explanation specific to this occurrence of the problem.
func Detail(detail string) Option {
return optionFunc(func(problem *Problem) {
problem.data["detail"] = detail
})
}
// Detailf A human readable explanation using a format string specific to this occurrence of the problem.
func Detailf(format string, values ...interface{}) Option {
return Detail(fmt.Sprintf(format, values...))
}
// Instance an absolute URI that identifies the specific occurrence of the
// problem.
func Instance(uri string) Option {
return optionFunc(func(problem *Problem) {
problem.data["instance"] = uri
})
}
// Instance an absolute URI using a format string that identifies the specific occurrence of the
// problem.
func Instancef(format string, values ...interface{}) Option {
return Instance(fmt.Sprintf(format, values...))
}
// Custom sets a custom key value
func Custom(key string, value interface{}) Option {
return optionFunc(func(problem *Problem) {
problem.data[key] = value
})
}