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"} jsonASCIIContentType = []string{"application/json"}
) )
var (
leftSquareBracket = bytesconv.StringToBytes("[")
rightSquareBracket = bytesconv.StringToBytes("]")
)
// Render (JSON) writes data with custom ContentType. // Render (JSON) writes data with custom ContentType.
func (r JSON) Render(w http.ResponseWriter) (err error) { func (r JSON) Render(w http.ResponseWriter) (err error) {
if err = WriteJSON(w, r.Data); err != nil { if err = WriteJSON(w, r.Data); err != nil {
@ -100,11 +105,8 @@ func (r SecureJSON) Render(w http.ResponseWriter) error {
return err return err
} }
// if the jsonBytes is array values // if the jsonBytes is array values
if bytes.HasPrefix(jsonBytes, bytesconv.StringToBytes("[")) && bytes.HasSuffix(jsonBytes, if bytes.HasPrefix(jsonBytes, leftSquareBracket) && bytes.HasSuffix(jsonBytes, rightSquareBracket) {
bytesconv.StringToBytes("]")) { jsonBytes = append(bytesconv.StringToBytes(r.Prefix), jsonBytes...)
if _, err = w.Write(bytesconv.StringToBytes(r.Prefix)); err != nil {
return err
}
} }
_, err = w.Write(jsonBytes) _, err = w.Write(jsonBytes)
return err return err
@ -128,26 +130,11 @@ func (r JsonpJSON) Render(w http.ResponseWriter) (err error) {
return err return err
} }
callback := template.JSEscapeString(r.Callback) jsonpData := fmt.Sprintf("%s(%s);", template.JSEscapeString(r.Callback), bytesconv.BytesToString(ret))
if _, err = w.Write(bytesconv.StringToBytes(callback)); err != nil { _, err = w.Write(bytesconv.StringToBytes(jsonpData))
return err 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. // WriteContentType (JsonpJSON) writes Javascript ContentType.
func (r JsonpJSON) WriteContentType(w http.ResponseWriter) { func (r JsonpJSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, jsonpContentType) writeContentType(w, jsonpContentType)