Skip to content

Commit

Permalink
Add context Writef feature function (#1841)
Browse files Browse the repository at this point in the history
  • Loading branch information
asyslinux committed Apr 1, 2022
1 parent 907fdfa commit 16b8717
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

1 comment on commit 16b8717

@Fenny
Copy link
Member

@Fenny Fenny commented on 16b8717 Apr 1, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 2.

Benchmark suite Current: 16b8717 Previous: 907fdfa Ratio
Benchmark_AcquireCtx 1213 ns/op 1440 B/op 5 allocs/op 586.8 ns/op 1440 B/op 5 allocs/op 2.07

This comment was automatically generated by workflow using github-action-benchmark.

Please sign in to comment.