/
json.go
52 lines (41 loc) · 1.21 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
package httplog
import (
"net/http"
"github.com/bingoohuang/strcase"
jsoniter "github.com/json-iterator/go"
"github.com/json-iterator/go/extra"
)
// nolint
var (
jsonContentType = []string{"application/json; charset=utf-8"}
JSONUnmarshal = jsoniter.Unmarshal
JSONMarshal = jsoniter.Marshal
JSONMarshalIndent = jsoniter.MarshalIndent
)
// JSON contains the given interface object.
type JSON struct {
Data interface{}
}
// Render (JSON) writes rowsData with custom ContentType.
func (r JSON) Render(w http.ResponseWriter) error {
return WriteJSON(w, r.Data)
}
// WriteContentType (JSON) writes JSON ContentType.
func (r JSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, jsonContentType)
}
// nolint:gochecknoinits
func init() {
extra.SetNamingStrategy(strcase.ToCamelLower)
}
// WriteJSON marshals the given interface object and writes it with custom ContentType.
func WriteJSON(w http.ResponseWriter, obj interface{}) error {
writeContentType(w, jsonContentType)
return jsoniter.NewEncoder(w).Encode(&obj)
}
func writeContentType(w http.ResponseWriter, value []string) {
header := w.Header()
if val := header["Content-Type"]; len(val) == 0 {
header["Content-Type"] = value
}
}