Skip to content

Commit

Permalink
Add context Writef feature function (gofiber#1841)
Browse files Browse the repository at this point in the history
  • Loading branch information
asyslinux authored and trim21 committed Aug 15, 2022
1 parent bd1f058 commit 458c712
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
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

0 comments on commit 458c712

Please sign in to comment.