Add io.Reader support

Co-Authored-By: Roman Kredentser <shareed2k@gmail.com>
pull/431/head
Fenny 2020-06-01 14:53:45 +02:00
parent 027823e084
commit 69596c03b9
2 changed files with 33 additions and 0 deletions

13
ctx.go
View File

@ -826,6 +826,16 @@ func (ctx *Ctx) SendString(body string) {
ctx.Fasthttp.Response.SetBodyString(body)
}
// SendStream sets response body stream and optional body size
func (ctx *Ctx) SendStream(stream io.Reader, size ...int) {
if len(size) > 0 && size[0] >= 0 {
ctx.Fasthttp.Response.SetBodyStream(stream, size[0])
} else {
ctx.Fasthttp.Response.SetBodyStream(stream, -1)
ctx.Set(HeaderContentLength, strconv.Itoa(len(ctx.Fasthttp.Response.Body())))
}
}
// Set sets the responses HTTP header field to the specified key, value.
func (ctx *Ctx) Set(key string, val string) {
ctx.Fasthttp.Response.Header.Set(key, val)
@ -879,6 +889,9 @@ func (ctx *Ctx) Write(bodies ...interface{}) {
ctx.Fasthttp.Response.AppendBodyString(strconv.Itoa(body))
case bool:
ctx.Fasthttp.Response.AppendBodyString(strconv.FormatBool(body))
case io.Reader:
ctx.Fasthttp.Response.SetBodyStream(body, -1)
ctx.Set(HeaderContentLength, strconv.Itoa(len(ctx.Fasthttp.Response.Body())))
default:
ctx.Fasthttp.Response.AppendBodyString(fmt.Sprintf("%v", body))
}

View File

@ -8,6 +8,7 @@ package fiber
// go test -run Test_Ctx
import (
"bufio"
"bytes"
"fmt"
"io"
@ -1063,6 +1064,25 @@ func Test_Ctx_SendString(t *testing.T) {
utils.AssertEqual(t, "Don't crash please", string(ctx.Fasthttp.Response.Body()))
}
// go test -run Test_Ctx_SendStream
func Test_Ctx_SendStream(t *testing.T) {
t.Parallel()
app := New()
ctx := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(ctx)
ctx.SendStream(bytes.NewReader([]byte("Don't crash please")))
utils.AssertEqual(t, "Don't crash please", string(ctx.Fasthttp.Response.Body()))
ctx.SendStream(bufio.NewReader(bytes.NewReader([]byte("Hello bufio"))))
utils.AssertEqual(t, "Hello bufio", string(ctx.Fasthttp.Response.Body()))
file, err := os.Open("./.github/index.html")
utils.AssertEqual(t, nil, err)
ctx.SendStream(bufio.NewReader(file))
utils.AssertEqual(t, "227", string(ctx.Fasthttp.Response.Header.Peek("Content-Length")))
}
// go test -run Test_Ctx_Set
func Test_Ctx_Set(t *testing.T) {
t.Parallel()