mirror of
https://github.com/valyala/fasthttp.git
synced 2026-06-14 15:56:44 +03:00
Added BodyWrite() to Request and Response for writing request and response bodies
This commit is contained in:
@@ -78,6 +78,38 @@ func (resp *Response) SetBodyStream(bodyStream io.Reader, bodySize int) {
|
||||
resp.Header.SetContentLength(bodySize)
|
||||
}
|
||||
|
||||
// BodyWriter returns writer for populating response body.
|
||||
func (resp *Response) BodyWriter() io.Writer {
|
||||
return responseBodyWriter{
|
||||
Response: resp,
|
||||
}
|
||||
}
|
||||
|
||||
// BodyWriter returns writer for populating request body.
|
||||
func (req *Request) BodyWriter() io.Writer {
|
||||
return requestBodyWriter{
|
||||
Request: req,
|
||||
}
|
||||
}
|
||||
|
||||
type responseBodyWriter struct {
|
||||
*Response
|
||||
}
|
||||
|
||||
func (w responseBodyWriter) Write(p []byte) (int, error) {
|
||||
w.Response.body = append(w.body, p...)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
type requestBodyWriter struct {
|
||||
*Request
|
||||
}
|
||||
|
||||
func (w requestBodyWriter) Write(p []byte) (int, error) {
|
||||
w.Request.body = append(w.body, p...)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// Body returns response body.
|
||||
func (resp *Response) Body() []byte {
|
||||
return resp.body
|
||||
|
||||
@@ -8,6 +8,28 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRequestBodyWriter(t *testing.T) {
|
||||
var r Request
|
||||
w := r.BodyWriter()
|
||||
for i := 0; i < 10; i++ {
|
||||
fmt.Fprintf(w, "%d", i)
|
||||
}
|
||||
if string(r.Body()) != "0123456789" {
|
||||
t.Fatalf("unexpected body %q. Expecting %q", r.Body(), "0123456789")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponseBodyWriter(t *testing.T) {
|
||||
var r Response
|
||||
w := r.BodyWriter()
|
||||
for i := 0; i < 10; i++ {
|
||||
fmt.Fprintf(w, "%d", i)
|
||||
}
|
||||
if string(r.Body()) != "0123456789" {
|
||||
t.Fatalf("unexpected body %q. Expecting %q", r.Body(), "0123456789")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestWriteRequestURINoHost(t *testing.T) {
|
||||
var req Request
|
||||
req.Header.SetRequestURI("http://google.com/foo/bar?baz=aaa")
|
||||
|
||||
Reference in New Issue
Block a user