From 5393fa858ab24529420e558c8b6600cde66697c2 Mon Sep 17 00:00:00 2001 From: mstmdev Date: Mon, 21 Mar 2022 02:43:14 +0800 Subject: [PATCH] Merge the write operation for json render and improve the code coverage --- render/json.go | 33 ++++++++++----------------------- 1 file changed, 10 insertions(+), 23 deletions(-) diff --git a/render/json.go b/render/json.go index 3ebcee97..f1f8a6ae 100644 --- a/render/json.go +++ b/render/json.go @@ -52,6 +52,11 @@ var ( jsonASCIIContentType = []string{"application/json"} ) +var ( + leftSquareBracket = bytesconv.StringToBytes("[") + rightSquareBracket = bytesconv.StringToBytes("]") +) + // Render (JSON) writes data with custom ContentType. func (r JSON) Render(w http.ResponseWriter) (err error) { if err = WriteJSON(w, r.Data); err != nil { @@ -100,11 +105,8 @@ func (r SecureJSON) Render(w http.ResponseWriter) error { return err } // if the jsonBytes is array values - if bytes.HasPrefix(jsonBytes, bytesconv.StringToBytes("[")) && bytes.HasSuffix(jsonBytes, - bytesconv.StringToBytes("]")) { - if _, err = w.Write(bytesconv.StringToBytes(r.Prefix)); err != nil { - return err - } + if bytes.HasPrefix(jsonBytes, leftSquareBracket) && bytes.HasSuffix(jsonBytes, rightSquareBracket) { + jsonBytes = append(bytesconv.StringToBytes(r.Prefix), jsonBytes...) } _, err = w.Write(jsonBytes) return err @@ -128,24 +130,9 @@ func (r JsonpJSON) Render(w http.ResponseWriter) (err error) { return err } - callback := template.JSEscapeString(r.Callback) - if _, err = w.Write(bytesconv.StringToBytes(callback)); err != nil { - return err - } - - if _, err = w.Write(bytesconv.StringToBytes("(")); err != nil { - return err - } - - if _, err = w.Write(ret); err != nil { - return err - } - - if _, err = w.Write(bytesconv.StringToBytes(");")); err != nil { - return err - } - - return nil + jsonpData := fmt.Sprintf("%s(%s);", template.JSEscapeString(r.Callback), bytesconv.BytesToString(ret)) + _, err = w.Write(bytesconv.StringToBytes(jsonpData)) + return err } // WriteContentType (JsonpJSON) writes Javascript ContentType.