From cecfb0d788f1caf12ecad771e9ded5300a537b03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Fri, 5 May 2023 14:43:40 +0200 Subject: [PATCH] v0.0.108 --- gojson/encode.go | 19 +++++++++++++++++-- gojson/gionic.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 gojson/gionic.go diff --git a/gojson/encode.go b/gojson/encode.go index ba013ed..9f521e1 100644 --- a/gojson/encode.go +++ b/gojson/encode.go @@ -167,15 +167,30 @@ func Marshal(v any) ([]byte, error) { return buf, nil } +type IndentOpt struct { + Prefix string + Indent string +} + // MarshalSafeCollections is like Marshal except it will marshal nil maps and // slices as '{}' and '[]' respectfully instead of 'null' -func MarshalSafeCollections(v interface{}, nilSafeSlices bool, nilSafeMaps bool) ([]byte, error) { +func MarshalSafeCollections(v interface{}, nilSafeSlices bool, nilSafeMaps bool, indent *IndentOpt) ([]byte, error) { e := &encodeState{} err := e.marshal(v, encOpts{escapeHTML: true, nilSafeSlices: nilSafeSlices, nilSafeMaps: nilSafeMaps}) if err != nil { return nil, err } - return e.Bytes(), nil + b := e.Bytes() + if indent != nil { + var buf bytes.Buffer + err = Indent(&buf, b, indent.Prefix, indent.Indent) + if err != nil { + return nil, err + } + return buf.Bytes(), nil + } else { + return e.Bytes(), nil + } } // MarshalIndent is like Marshal but applies Indent to format the output. diff --git a/gojson/gionic.go b/gojson/gionic.go new file mode 100644 index 0000000..2bd18f9 --- /dev/null +++ b/gojson/gionic.go @@ -0,0 +1,44 @@ +package json + +import ( + "net/http" +) + +// Render interface is copied from github.com/gin-gonic/gin@v1.8.1/render/render.go +type Render interface { + // Render writes data with custom ContentType. + Render(http.ResponseWriter) error + // WriteContentType writes custom ContentType. + WriteContentType(w http.ResponseWriter) +} + +type GoJsonRender struct { + Data any + NilSafeSlices bool + NilSafeMaps bool + Indent *IndentOpt +} + +func (r GoJsonRender) Render(w http.ResponseWriter) error { + header := w.Header() + if val := header["Content-Type"]; len(val) == 0 { + header["Content-Type"] = []string{"application/json; charset=utf-8"} + } + + jsonBytes, err := MarshalSafeCollections(r.Data, r.NilSafeSlices, r.NilSafeMaps, r.Indent) + if err != nil { + panic(err) + } + _, err = w.Write(jsonBytes) + if err != nil { + panic(err) + } + return nil +} + +func (r GoJsonRender) WriteContentType(w http.ResponseWriter) { + header := w.Header() + if val := header["Content-Type"]; len(val) == 0 { + header["Content-Type"] = []string{"application/json; charset=utf-8"} + } +}