Skip to content

Commit

Permalink
fix: set content-length properly when StreanRequestBody was enabled (#…
Browse files Browse the repository at this point in the history
…1049)

* fix: set content-length properly when StreanRequestBody was enabled

* fix: add test cases for validating content length of streaming request
  • Loading branch information
lemonlinger authored Jun 18, 2021
1 parent cec9953 commit 4ed933a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
2 changes: 1 addition & 1 deletion http.go
Original file line number Diff line number Diff line change
Expand Up @@ -1185,7 +1185,7 @@ func (req *Request) ContinueReadBodyStream(r *bufio.Reader, maxBodySize int, pre

req.body = bodyBuf
req.bodyStream = acquireRequestStream(bodyBuf, r, contentLength)
req.Header.SetContentLength(len(bodyBuf.B))
req.Header.SetContentLength(contentLength)
return nil
}

Expand Down
42 changes: 41 additions & 1 deletion server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1108,7 +1108,6 @@ Host: asbd
Connection: close
`

ln := fasthttputil.NewInmemoryListener()

s := &Server{
Expand Down Expand Up @@ -3578,6 +3577,47 @@ func TestStreamRequestBodyExceedMaxSize(t *testing.T) {
}
}

func TestStreamBodyReqestContentLength(t *testing.T) {
t.Parallel()
content := strings.Repeat("1", 1<<15) // 32K
contentLength := len(content)

s := &Server{
Handler: func(ctx *RequestCtx) {
realContentLength := ctx.Request.Header.ContentLength()
if realContentLength != contentLength {
t.Fatal("incorrect content length")
}
},
MaxRequestBodySize: 1 * 1024 * 1024, // 1M
StreamRequestBody: true,
}

pipe := fasthttputil.NewPipeConns()
cc, sc := pipe.Conn1(), pipe.Conn2()
if _, err := cc.Write([]byte(fmt.Sprintf("POST /foo2 HTTP/1.1\r\nHost: aaa.com\r\nContent-Length: %d\r\nContent-Type: aa\r\n\r\n%s", contentLength, content))); err != nil {
t.Fatal(err)
}

ch := make(chan error)
go func() {
ch <- s.ServeConn(sc)
}()

if err := sc.Close(); err != nil {
t.Fatal(err)
}

select {
case err := <-ch:
if err == nil || err.Error() != "connection closed" { // fasthttputil.errConnectionClosed is private so do a string match.
t.Fatalf("Unexpected error from serveConn: %s", err)
}
case <-time.After(time.Second):
t.Fatal("test timeout")
}
}

func checkReader(t *testing.T, r io.Reader, expected string) {
b := make([]byte, len(expected))
if _, err := io.ReadFull(r, b); err != nil {
Expand Down

0 comments on commit 4ed933a

Please sign in to comment.