forked from yaitoo/xun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviewer_json.go
More file actions
40 lines (33 loc) · 958 Bytes
/
viewer_json.go
File metadata and controls
40 lines (33 loc) · 958 Bytes
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(ctx *Context, data any) error { // skipcq: RVV-B0012
var err error
ctx.Response.Header().Set("Content-Type", "application/json")
if ctx.Request.Method != http.MethodHead {
buf := BufPool.Get()
defer BufPool.Put(buf)
err = Json.NewEncoder(buf).Encode(data)
if err != nil {
return err
}
_, err = buf.WriteTo(ctx.Response)
}
return err
}