Repository: go
Issue: net/http: Request context is not canceled when `Server.WriteTimeout` is reached
Labels: NeedsInvestigation

<!--
Please answer these questions before submitting your issue. Thanks!
-->

### What version of Go are you using (`go version`)?

<pre>
$ go version
go version go1.19.5 linux/amd64
</pre>

### Does this issue reproduce with the latest release?

yes

### What operating system and processor architecture are you using (`go env`)?

<details><summary><code>go env</code> Output</summary><br><pre>
$ go env
GO111MODULE="on"
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/patrik/.cache/go-build"
GOENV="/home/patrik/.config/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GOMODCACHE="/home/patrik/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/patrik/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/lib/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
GOVCS=""
GOVERSION="go1.19.5"
GCCGO="gccgo"
GOAMD64="v1"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/home/patrik/git/oathkeeper/go.mod"
GOWORK=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -Wl,--no-gc-sections -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build1543900704=/tmp/go-build -gno-record-gcc-switches"
</pre></details>

### What did you do?

<!--
If possible, provide a recipe for reproducing the error.
A complete runnable program is good.
A link on go.dev/play is best.
-->

```go
func TestWriteTimeoutCancellation(t *testing.T) {
	backend := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.Body.Close() // to show that it is not https://github.com/golang/go/issues/23262

		time.Sleep(1 * time.Second)
		_, err := w.Write([]byte("ok"))
		ctxErr := r.Context().Err()

		_, _ = ctxErr, err // breakpoint here to see the errors, they are both nil
	}))
	backend.Config.WriteTimeout = 500 * time.Millisecond
	backend.EnableHTTP2 = true // you can also try false

	backend.Start()
	defer backend.Close()

	start := time.Now()
	res, err := backend.Client().Get(backend.URL)
	t.Logf("took %s", time.Since(start)) // for me this always takes 1s, although the write timeout is 500ms
	_, _ = res, err // breakpoint here, err is EOF, res is nil
}
```

### What did you expect to see?

Client side: all requests are cancelled latest after the write timeout, why wait until the handler is done to not receive the result?
Handler side: `r.Context()` is cancelled, so it can stop handling because the result is not returned anyway

I have seen https://github.com/golang/go/issues/21389 which is kinda related, but not the same issue. I do understand that `w.Write()` does not immediately return an error because of buffering. I would expect the request context to be canceled immediately though.

### What did you see instead?

Client: request took 1s, although the write timeout is 500ms
Handler: no way to tell whether the timeout was triggered, potentially expensive or destructive work continues

As is, I don't understand the use of `WriteTimeout` at all. It seems there is no effect, except for maybe big responses that might already be partially received by the client (see https://github.com/traefik/traefik/issues/9191#issuecomment-1197891601).

I don't think this is a duplicate of #23262 because I see the behavior also when closing the body immediately.

### Workaround

It seems pretty simple to just write a middleware that wraps the request context with a timeout:

```go
func timeoutMiddleware(timeout time.Duration, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := context.WithTimeout(r.Context(), timeout)
		defer cancel()
		r = r.WithContext(ctx)
		next.ServeHTTP(w, r)
	})
}
```
cc @alnr