Skip to content

Commit

Permalink
Merge pull request #583 from Fenny/master
Browse files Browse the repository at this point in the history
🚀 Improve JSON response
  • Loading branch information
Fenny authored Jul 11, 2020
2 parents a8ad545 + 11b4ae3 commit a6d3337
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
6 changes: 3 additions & 3 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ func (ctx *Ctx) Format(body interface{}) {
ctx.Send(body) // Fallback
log.Println("Format: error serializing xml ", err)
} else {
ctx.SendString(getString(raw))
ctx.Fasthttp.Response.SetBodyRaw(raw)
}
default:
ctx.SendString(b)
Expand Down Expand Up @@ -515,8 +515,8 @@ func (ctx *Ctx) JSON(data interface{}) error {
}
// Set http headers
ctx.Fasthttp.Response.Header.SetContentType(MIMEApplicationJSON)
ctx.SendString(getString(raw))
// Success!
ctx.Fasthttp.Response.SetBodyRaw(raw)

return nil
}

Expand Down
28 changes: 28 additions & 0 deletions ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1472,3 +1472,31 @@ func Benchmark_Ctx_SendBytes_With_SetBodyRaw(b *testing.B) {
}
utils.AssertEqual(b, body, c.Fasthttp.Response.Body())
}

// go test -v -run=^$ -bench=Benchmark_Ctx_SendString_B -benchmem -count=4
func Benchmark_Ctx_SendString_B(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)
body := "Hello, world!"
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.SendString(body)
}
utils.AssertEqual(b, []byte("Hello, world!"), c.Fasthttp.Response.Body())
}

// go test -v -run=^$ -bench=Benchmark_Ctx_SendBytes_B -benchmem -count=4
func Benchmark_Ctx_SendBytes_B(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)
body := []byte("Hello, world!")
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.SendBytes(body)
}
utils.AssertEqual(b, []byte("Hello, world!"), c.Fasthttp.Response.Body())
}

0 comments on commit a6d3337

Please sign in to comment.