// 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
+ }
rw.writeHeader(buf, "")
if rw.Body != nil {
rw.Body.Write(buf)
// 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
+ }
rw.writeHeader(nil, str)
if rw.Body != nil {
rw.Body.WriteString(str)
return len(str), nil
}
+// bodyAllowedForStatus reports whether a given response status code
+// permits a body. See RFC 7230, section 3.3.
+func bodyAllowedForStatus(status int) bool {
+ switch {
+ case status >= 100 && status <= 199:
+ return false
+ case status == 204:
+ return false
+ case status == 304:
+ return false
+ }
+ return true
+}
+
func checkWriteHeaderCode(code int) {
// Issue 22880: require valid WriteHeader status codes.
// For now we only enforce that it's three digits.
package httptest
import (
+ "errors"
"fmt"
"io"
"net/http"
}
}
+func TestBodyNotAllowed(t *testing.T) {
+ rw := NewRecorder()
+ rw.WriteHeader(204)
+
+ _, err := rw.Write([]byte("hello world"))
+ if !errors.Is(err, http.ErrBodyNotAllowed) {
+ t.Errorf("expected BodyNotAllowed for Write after 204, got: %v", err)
+ }
+
+ _, err = rw.WriteString("hello world")
+ if !errors.Is(err, http.ErrBodyNotAllowed) {
+ t.Errorf("expected BodyNotAllowed for WriteString after 204, got: %v", err)
+ }
+}
+
// issue 39017 - disallow Content-Length values such as "+3"
func TestParseContentLength(t *testing.T) {
tests := []struct {