According to
https://golang.org/pkg/net/http/#Request.Context:
For incoming server requests, the context is canceled when the client's connection closes, the request is canceled (with HTTP/2), or when the ServeHTTP method returns.
My expectation, then, is for the following code to block:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
s := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ioutil.ReadAll(r.Body)
<-r.Context().Done()
w.Write([]byte(fmt.Sprintf(
"request context done: %+v\n",
r.Context().Err(),
)))
}),
}
s.ListenAndServe()
}
Instead, it always returns immediately, reporting that the context was canceled:
> printf "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 4\r\n\r\nbody" | nc localhost 8080
HTTP/1.1 200 OK
Date: Mon, 15 Jan 2018 16:01:46 GMT
Content-Length: 39
Content-Type: text/plain; charset=utf-8
request context done: context canceled
Curiously, if I don't ioutil.ReadAll(r.Body), the request blocks as expected.
Am I missing something? My hope was to be able to use the default context to detect client disconnection.