diff --git a/ctx.go b/ctx.go index 6181ad6996..be4168e0b7 100644 --- a/ctx.go +++ b/ctx.go @@ -1474,6 +1474,11 @@ func (c *Ctx) Write(p []byte) (int, error) { return len(p), nil } +// Writef appends f & a into response body writer. +func (c *Ctx) Writef(f string, a ...interface{}) (int, error) { + return fmt.Fprintf(c.fasthttp.Response.BodyWriter(), f, a...) +} + // WriteString appends s to response body. func (c *Ctx) WriteString(s string) (int, error) { c.fasthttp.Response.AppendBodyString(s) diff --git a/ctx_test.go b/ctx_test.go index 72c2826425..b9b4f11d63 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -2831,6 +2831,30 @@ func Benchmark_Ctx_Write(b *testing.B) { } } +// go test -run Test_Ctx_Writef +func Test_Ctx_Writef(t *testing.T) { + t.Parallel() + app := New() + c := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(c) + world := "World!" + c.Writef("Hello, %s", world) + utils.AssertEqual(t, "Hello, World!", string(c.Response().Body())) +} + +// go test -v -run=^$ -bench=Benchmark_Ctx_Writef -benchmem -count=4 +func Benchmark_Ctx_Writef(b *testing.B) { + app := New() + c := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(c) + world := "World!" + b.ReportAllocs() + b.ResetTimer() + for n := 0; n < b.N; n++ { + c.Writef("Hello, %s", world) + } +} + // go test -run Test_Ctx_WriteString func Test_Ctx_WriteString(t *testing.T) { t.Parallel()