-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem.go
210 lines (171 loc) · 5.82 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
package problem
import (
"bytes"
"fmt"
"net/http"
tme_json "github.com/otaxhu/type-mismatch-encoding/encoding/json"
tme_xml "github.com/otaxhu/type-mismatch-encoding/encoding/xml"
)
// Problem details interface, valid implementors are [MapProblem], [RegisteredProblem] and
// Custom structs that embeds [RegisteredProblem] (is recommended you embed by value, not a pointer,
// in that case you need to allocate appropriate memory for that field)
type Problem interface {
GetType() string
GetStatus() int
GetTitle() string
GetDetail() string
GetInstance() string
// For taking status code from Response object instead of status in problem details body.
//
// Also works as a "Must embed" method when creating customs Problems, customs Problems
// must embed [RegisteredProblem]
setStatus(status int)
// For setting "about:blank" to type when the problem detail's type member is not present or
// has a JSON type other than string.
setTypeAboutBlank()
}
// NewMap returns a [MapProblem], this implementation is ONLY suitable for JSON
// marshaling/unmarshaling.
//
// If you want XML support, Instead you should use [NewRegistered] or create your own custom
// struct that embeds [RegisteredProblem] and set the fields yourself.
func NewMap(statusCode int, details string) MapProblem {
return MapProblem{
"status": statusCode,
"detail": details,
"title": http.StatusText(statusCode),
"type": "about:blank",
}
}
// NewRegistered returns a *[RegisteredProblem], this implementation is suitable for both
// XML and JSON marshaling/unmarshaling.
//
// If you want to add extension members (extra members others than the specified in
// https://datatracker.ietf.org/doc/html/rfc9457#name-members-of-a-problem-detail)
// then you will need to use [NewMap] or create your own custom struct that embeds
// [RegisteredProblem] and set the fields yourself.
func NewRegistered(statusCode int, details string) *RegisteredProblem {
return &RegisteredProblem{
Type: "about:blank",
Status: statusCode,
Title: http.StatusText(statusCode),
Detail: details,
}
}
// ParseResponse parses the [http.Response] object into a Problem details.
// The Content-Type header of the response determines the implementation used
//
// 1. If Content-Type is 'application/problem+json' (Problem JSON) then the type of the returned
// Problem is *[MapProblem] (a pointer)
//
// 2. Else if Content-Type is 'application/problem+xml' (Problem XML) then the type of the
// returned Problem is *[RegisteredProblem] (a pointer) and found extension members are
// ignored.
//
// If Content-Type is not one of the first two above, then an error [ErrInvalidContentType] is
// returned, you can check for it using errors.Is(err, ErrInvalidContentType)
func ParseResponse(res *http.Response) (Problem, error) {
contentType := res.Header.Get("Content-Type")
var p Problem
if contentType == MediaTypeProblemJSON {
// Use a MapProblem
p = &MapProblem{}
} else if contentType == MediaTypeProblemXML {
// Use RegisteredProblem, gonna lost extension members but it's better than failing
p = &RegisteredProblem{}
} else {
return nil, fmt.Errorf("%w: got '%s'", ErrInvalidContentType, contentType)
}
err := ParseResponseCustom(res, p)
if err != nil {
return nil, err
}
return p, nil
}
// ParseResponseCustom parses the [http.Response] object, unmarshaling it into p argument.
//
// There are some contraints you need to follow in order for this function to work.
//
// - p must be a pointer.
// - p must not be nil nor point to nil.
// - If Content-Type is 'application/problem+xml' (Problem XML), then p must not be a [MapProblem]
//
// If you followed this constraints, then you should get p populated with the Problem details
// values and no errors.
func ParseResponseCustom(res *http.Response, p Problem) error {
contentType := res.Header.Get("Content-Type")
if contentType != MediaTypeProblemJSON && contentType != MediaTypeProblemXML {
return fmt.Errorf("%w: got '%s'", ErrInvalidContentType, contentType)
}
buf := getBuffer()
defer bufferPool.Put(buf)
_, err := buf.ReadFrom(res.Body)
res.Body.Close()
if err != nil {
return err
}
b := buf.Bytes()
// See issue https://github.com/otaxhu/problem/issues/14
//
// This structs checks that "type" is present or has an incorrect type (on JSON)
// and act accordingly by setting "type" to "about:blank"
//
// RFC 9457 Section 3.1 https://www.rfc-editor.org/rfc/rfc9457.html#section-3.1-1
//
// "...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."
//
// RFC 9457 Section 3.1.1 https://www.rfc-editor.org/rfc/rfc9457.html#section-3.1.1-2
//
// "When this member ("type") is not present, its value is assumed to be "about:blank"."
checkTypeJSON := struct {
Type any `json:"type"`
}{}
checkTypeXML := struct {
XMLName struct{} `xml:"urn:ietf:rfc:7807 problem"`
Type *string `xml:"type"`
}{}
br := bytes.NewReader(b)
switch contentType {
case MediaTypeProblemJSON:
dec := tme_json.NewDecoder(br)
dec.AllowTypeMismatch()
err := dec.Decode(p)
if err != nil {
return err
}
if p.GetType() == "" {
br.Reset(b)
dec = tme_json.NewDecoder(br)
dec.AllowTypeMismatch()
err = dec.Decode(&checkTypeJSON)
if err != nil {
return err
}
if _, ok := checkTypeJSON.Type.(string); !ok {
p.setTypeAboutBlank()
}
}
case MediaTypeProblemXML:
dec := tme_xml.NewDecoder(br)
dec.AllowTypeMismatch = true
err := dec.Decode(p)
if err != nil {
return err
}
if p.GetType() == "" {
br.Reset(b)
dec = tme_xml.NewDecoder(br)
dec.AllowTypeMismatch = true
err = dec.Decode(&checkTypeXML)
if err != nil {
return err
}
if checkTypeXML.Type == nil {
p.setTypeAboutBlank()
}
}
}
p.setStatus(res.StatusCode)
return nil
}