-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathviewer_json.go
40 lines (33 loc) · 952 Bytes
/
viewer_json.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
package xun
import (
"net/http"
)
// JsonViewer is a viewer that writes the given data as JSON to the http.ResponseWriter.
//
// It sets the Content-Type header to "application/json".
type JsonViewer struct {
}
var jsonViewerMime = &MimeType{Type: "application", SubType: "json"}
// MimeType returns the MIME type of the JSON content.
//
// It returns "application/json".
func (*JsonViewer) MimeType() *MimeType {
return jsonViewerMime
}
// Render renders the given data as JSON to the http.ResponseWriter.
//
// It sets the Content-Type header to "application/json".
func (*JsonViewer) Render(w http.ResponseWriter, r *http.Request, data any) error { // skipcq: RVV-B0012
var err error
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodHead {
buf := BufPool.Get()
defer BufPool.Put(buf)
err = json.NewEncoder(buf).Encode(data)
if err != nil {
return err
}
_, err = buf.WriteTo(w)
}
return err
}