Can sending a Content-Length header greater than the actual content hang the copy operations in Golang?

Viewed 32

The following code hangs the curl client and the read operation when the Content-Length header is greater than the actual content itself.

package main

import (
    "fmt"
    "io"
    "net/http"
)

func main() {
    err := http.ListenAndServe("localhost:8080", http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
        defer request.Body.Close()
        fmt.Println("Body:")
        bb := make([]byte, 1)
        for {
            n, err := request.Body.Read(bb) //code hangs here after reading 2 bytes, because Read does not return
            if err == io.EOF {
                break
            }
            if err != nil {
                fmt.Println("Error reading:", err.Error())
                break
            }
            fmt.Printf("Read %d bytes => %q\n", n, bb)
        }
        fmt.Println("Copied")
        _, _ = fmt.Fprintln(writer, "hello")
    }))
    if err != nil {
        panic(err)
    }

}

Curl call

curl -vv -d '{}' -H 'Content-Length:3' localhost:8080

If the actual Content-Length:2 is specified, the code works fine. When Content-Length is less than or equal to the actual Content-Length the code works as exepcted, but if it is greater than it then I cannot read the body

0 Answers
Related