// Write implements http.ResponseWriter. The data in buf is written to
// rw.Body, if not nil.
func (rw *ResponseRecorder) Write(buf []byte) (int, error) {
- code := rw.Code
- if !bodyAllowedForStatus(code) {
- return 0, http.ErrBodyNotAllowed
- }
+ // Record the write, even if we're going to return an error.
rw.writeHeader(buf, "")
if rw.Body != nil {
rw.Body.Write(buf)
}
+ if !bodyAllowedForStatus(rw.Code) {
+ return 0, http.ErrBodyNotAllowed
+ }
return len(buf), nil
}
// WriteString implements [io.StringWriter]. The data in str is written
// to rw.Body, if not nil.
func (rw *ResponseRecorder) WriteString(str string) (int, error) {
- code := rw.Code
- if !bodyAllowedForStatus(code) {
- return 0, http.ErrBodyNotAllowed
- }
+ // Record the write, even if we're going to return an error.
rw.writeHeader(nil, str)
if rw.Body != nil {
rw.Body.WriteString(str)
}
+ if !bodyAllowedForStatus(rw.Code) {
+ return 0, http.ErrBodyNotAllowed
+ }
return len(str), nil
}
package httptest
import (
+ "bytes"
"errors"
"fmt"
"io"
func TestBodyNotAllowed(t *testing.T) {
rw := NewRecorder()
+ rw.Body = new(bytes.Buffer)
rw.WriteHeader(204)
- _, err := rw.Write([]byte("hello world"))
+ _, err := rw.Write([]byte("hello "))
if !errors.Is(err, http.ErrBodyNotAllowed) {
t.Errorf("expected BodyNotAllowed for Write after 204, got: %v", err)
}
- _, err = rw.WriteString("hello world")
+ _, err = rw.WriteString("world")
if !errors.Is(err, http.ErrBodyNotAllowed) {
t.Errorf("expected BodyNotAllowed for WriteString after 204, got: %v", err)
}
+
+ if got, want := rw.Body.String(), "hello world"; got != want {
+ t.Errorf("got Body=%q, want %q", got, want)
+ }
}
// issue 39017 - disallow Content-Length values such as "+3"