Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add context Writef feature function #1841

Merged
merged 1 commit into from Apr 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions ctx.go
Expand Up @@ -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)
Expand Down
24 changes: 24 additions & 0 deletions ctx_test.go
Expand Up @@ -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()
Expand Down