]> Cypherpunks repositories - gostls13.git/commitdiff
net/http: remove Content-Length header in http.Error
authorDamien Neil <dneil@google.com>
Sat, 6 Jan 2024 00:10:33 +0000 (16:10 -0800)
committerDamien Neil <dneil@google.com>
Thu, 29 Feb 2024 19:48:56 +0000 (19:48 +0000)
Error replies to a request with an error message and HTTP code.
Delete any preexisting Content-Length header before writing the header;
if a Content-Length is present, it's probably for content that the
caller has given up on writing.

For #50905

Change-Id: Ia3d4ca008be46fa5d41afadf29ca5cacb1c47660
Reviewed-on: https://go-review.googlesource.com/c/go/+/554216
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
src/net/http/serve_test.go
src/net/http/server.go

index 69d105ec63f89b36473e97fa409dfba13578bd5c..9df6ab426ce80d4bdb2d924c7b90513fed980314 100644 (file)
@@ -7052,3 +7052,24 @@ func testDisableContentLength(t *testing.T, mode testMode) {
                t.Fatal(err)
        }
 }
+
+func TestErrorContentLength(t *testing.T) { run(t, testErrorContentLength) }
+func testErrorContentLength(t *testing.T, mode testMode) {
+       const errorBody = "an error occurred"
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+               w.Header().Set("Content-Length", "1000")
+               Error(w, errorBody, 400)
+       }))
+       res, err := cst.c.Get(cst.ts.URL)
+       if err != nil {
+               t.Fatalf("Get(%q) = %v", cst.ts.URL, err)
+       }
+       defer res.Body.Close()
+       body, err := io.ReadAll(res.Body)
+       if err != nil {
+               t.Fatalf("io.ReadAll(res.Body) = %v", err)
+       }
+       if string(body) != errorBody+"\n" {
+               t.Fatalf("read body: %q, want %q", string(body), errorBody)
+       }
+}
index 7d73cca43fd21f0dbb4955f06aeabbcfc596f8c1..bd7cce6793e94595fb4ebb72f4d514647032f8dd 100644 (file)
@@ -2173,6 +2173,7 @@ func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
 // writes are done to w.
 // The error message should be plain text.
 func Error(w ResponseWriter, error string, code int) {
+       w.Header().Del("Content-Length")
        w.Header().Set("Content-Type", "text/plain; charset=utf-8")
        w.Header().Set("X-Content-Type-Options", "nosniff")
        w.WriteHeader(code)