-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
74 lines (62 loc) · 1.66 KB
/
http.go
File metadata and controls
74 lines (62 loc) · 1.66 KB
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
package problem
import (
"bytes"
"encoding/json"
"encoding/xml"
"net/http"
"strconv"
"sync"
)
type problemHTTPWrapper struct {
p Problem
contentType string
}
var bufferPool = sync.Pool{
New: func() any {
return &bytes.Buffer{}
},
}
func getBuffer() *bytes.Buffer {
buf := bufferPool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}
func (p *problemHTTPWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
buf := getBuffer()
defer bufferPool.Put(buf)
h := w.Header()
switch p.contentType {
case MediaTypeProblemJSON:
_ = json.NewEncoder(buf).Encode(p.p)
case MediaTypeProblemXML:
buf.WriteString(xml.Header)
_ = xml.NewEncoder(buf).Encode(p.p)
}
h.Set("Content-Type", p.contentType)
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Content-Length", strconv.Itoa(buf.Len()))
w.WriteHeader(p.p.GetStatus())
_, _ = buf.WriteTo(w)
}
// ServeXML returns a Handler that serves the p argument in XML format.
//
// p MUST not be a [MapProblem], since it cannot be marshaled to XML.
//
// Headers Content-Type is set to 'application/problem+xml' and X-Content-Type-Options is set to 'nosniff';
// and finally writes the status code from p.GetStatus().
func ServeXML(p Problem) http.Handler {
return &problemHTTPWrapper{
p: p,
contentType: MediaTypeProblemXML,
}
}
// ServeJSON returns a Handler that serves the p argument in JSON format
//
// Headers Content-Type is set to 'application/problem+json' and X-Content-Type-Options is set to
// 'nosniff'; and finally writes the status code from p.GetStatus().
func ServeJSON(p Problem) http.Handler {
return &problemHTTPWrapper{
p: p,
contentType: MediaTypeProblemJSON,
}
}