🚀 remove & to improve ctx.JSON(😭)

This commit is contained in:
kiyon 2020-07-11 16:35:52 +08:00
parent 30ac2a8e6c
commit 5175222c03
2 changed files with 6 additions and 52 deletions

31
ctx.go
View File

@ -508,38 +508,15 @@ func (ctx *Ctx) Is(extension string) bool {
// JSON converts any interface or string to JSON.
// This method also sets the content header to application/json.
func (ctx *Ctx) JSON(data interface{}) error {
// Reset response body
ctx.Fasthttp.Response.ResetBody()
encoder := json.NewEncoder(ctx.Fasthttp.Response.BodyWriter())
encoder.SetEscapeHTML(true)
// Write data to response body writer directly
if err := encoder.Encode(data); err != nil {
return err
}
// Set http headers
ctx.Fasthttp.Response.Header.SetContentType(MIMEApplicationJSON)
b := ctx.Fasthttp.Response.Body()
if end := len(b) - 1; end >= 0 && b[end] == '\n' {
// remove extra '\n' added by encoder.Encode
ctx.Fasthttp.Response.SetBodyRaw(b[:end])
}
// Success!
return nil
}
// JSON converts any interface or string to JSON using Jsoniter.
// This method also sets the content header to application/json.
func (ctx *Ctx) JSONOld(data interface{}) error {
raw, err := json.Marshal(&data)
raw, err := json.Marshal(data)
// Check for errors
if err != nil {
return err
}
// Set http headers
ctx.Fasthttp.Response.Header.SetContentType(MIMEApplicationJSON)
ctx.SendString(getString(raw))
// For TFB !!!
ctx.Fasthttp.Response.SetBodyRaw(raw)
// Success!
return nil
}
@ -548,7 +525,7 @@ func (ctx *Ctx) JSONOld(data interface{}) error {
// This method is identical to JSON, except that it opts-in to JSONP callback support.
// By default, the callback name is simply callback.
func (ctx *Ctx) JSONP(data interface{}, callback ...string) error {
raw, err := json.Marshal(&data)
raw, err := json.Marshal(data)
if err != nil {
return err

View File

@ -1023,30 +1023,7 @@ func Benchmark_Ctx_JSON(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
err = c.JSON(data)
}
utils.AssertEqual(b, nil, err)
utils.AssertEqual(b, `{"Name":"Grame","Age":20}`, string(c.Fasthttp.Response.Body()))
}
// go test -v -run=^$ -bench=Benchmark_Ctx_JSONOld -benchmem -count=4
func Benchmark_Ctx_JSONOld(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)
type SomeStruct struct {
Name string
Age uint8
}
data := SomeStruct{
Name: "Grame",
Age: 20,
}
var err error
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
err = c.JSONOld(data)
err = c.JSON(&data)
}
utils.AssertEqual(b, nil, err)
utils.AssertEqual(b, `{"Name":"Grame","Age":20}`, string(c.Fasthttp.Response.Body()))
@ -1084,7 +1061,7 @@ func Benchmark_Ctx_JSONP(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
err = c.JSONP(data, callback)
err = c.JSONP(&data, callback)
}
utils.AssertEqual(b, nil, err)
utils.AssertEqual(b, `emit({"Name":"Grame","Age":20});`, string(c.Fasthttp.Response.Body()))