File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -105,6 +105,10 @@ func (rw *ResponseRecorder) writeHeader(b []byte, str string) {
105
105
// Write implements http.ResponseWriter. The data in buf is written to
106
106
// rw.Body, if not nil.
107
107
func (rw * ResponseRecorder ) Write (buf []byte ) (int , error ) {
108
+ code := rw .Code
109
+ if ! bodyAllowedForStatus (code ) {
110
+ return 0 , http .ErrBodyNotAllowed
111
+ }
108
112
rw .writeHeader (buf , "" )
109
113
if rw .Body != nil {
110
114
rw .Body .Write (buf )
@@ -115,13 +119,31 @@ func (rw *ResponseRecorder) Write(buf []byte) (int, error) {
115
119
// WriteString implements [io.StringWriter]. The data in str is written
116
120
// to rw.Body, if not nil.
117
121
func (rw * ResponseRecorder ) WriteString (str string ) (int , error ) {
122
+ code := rw .Code
123
+ if ! bodyAllowedForStatus (code ) {
124
+ return 0 , http .ErrBodyNotAllowed
125
+ }
118
126
rw .writeHeader (nil , str )
119
127
if rw .Body != nil {
120
128
rw .Body .WriteString (str )
121
129
}
122
130
return len (str ), nil
123
131
}
124
132
133
+ // bodyAllowedForStatus reports whether a given response status code
134
+ // permits a body. See RFC 7230, section 3.3.
135
+ func bodyAllowedForStatus (status int ) bool {
136
+ switch {
137
+ case status >= 100 && status <= 199 :
138
+ return false
139
+ case status == 204 :
140
+ return false
141
+ case status == 304 :
142
+ return false
143
+ }
144
+ return true
145
+ }
146
+
125
147
func checkWriteHeaderCode (code int ) {
126
148
// Issue 22880: require valid WriteHeader status codes.
127
149
// For now we only enforce that it's three digits.
Original file line number Diff line number Diff line change 5
5
package httptest
6
6
7
7
import (
8
+ "errors"
8
9
"fmt"
9
10
"io"
10
11
"net/http"
@@ -309,6 +310,21 @@ func TestRecorder(t *testing.T) {
309
310
}
310
311
}
311
312
313
+ func TestBodyNotAllowed (t * testing.T ) {
314
+ rw := NewRecorder ()
315
+ rw .WriteHeader (204 )
316
+
317
+ _ , err := rw .Write ([]byte ("hello world" ))
318
+ if ! errors .Is (err , http .ErrBodyNotAllowed ) {
319
+ t .Errorf ("expected BodyNotAllowed for Write after 204, got: %v" , err )
320
+ }
321
+
322
+ _ , err = rw .WriteString ("hello world" )
323
+ if ! errors .Is (err , http .ErrBodyNotAllowed ) {
324
+ t .Errorf ("expected BodyNotAllowed for WriteString after 204, got: %v" , err )
325
+ }
326
+ }
327
+
312
328
// issue 39017 - disallow Content-Length values such as "+3"
313
329
func TestParseContentLength (t * testing.T ) {
314
330
tests := []struct {
You can’t perform that action at this time.
0 commit comments