Merge the write operation for json render and improve the code coverage

This commit is contained in:
mstmdev 2022-03-21 02:43:14 +08:00
parent 9701b651b7
commit 5393fa858a
1 changed files with 10 additions and 23 deletions

View File

@ -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 {
jsonpData := fmt.Sprintf("%s(%s);", template.JSEscapeString(r.Callback), bytesconv.BytesToString(ret))
_, err = w.Write(bytesconv.StringToBytes(jsonpData))
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
}
// WriteContentType (JsonpJSON) writes Javascript ContentType.