return len(str), nil
}
+func checkWriteHeaderCode(code int) {
+ // Issue 22880: require valid WriteHeader status codes.
+ // For now we only enforce that it's three digits.
+ // In the future we might block things over 599 (600 and above aren't defined
+ // at https://httpwg.org/specs/rfc7231.html#status.codes)
+ // and we might block under 200 (once we have more mature 1xx support).
+ // But for now any three digits.
+ //
+ // We used to send "HTTP/1.1 000 0" on the wire in responses but there's
+ // no equivalent bogus thing we can realistically send in HTTP/2,
+ // so we'll consistently panic instead and help people find their bugs
+ // early. (We can't return an error from WriteHeader even if we wanted to.)
+ if code < 100 || code > 999 {
+ panic(fmt.Sprintf("invalid WriteHeader code %v", code))
+ }
+}
+
// WriteHeader implements http.ResponseWriter.
func (rw *ResponseRecorder) WriteHeader(code int) {
if rw.wroteHeader {
return
}
+
+ checkWriteHeaderCode(code)
rw.Code = code
rw.wroteHeader = true
if rw.HeaderMap == nil {
}
}
}
+
+// Ensure that httptest.Recorder panics when given a non-3 digit (XXX)
+// status HTTP code. See https://golang.org/issues/45353
+func TestRecorderPanicsOnNonXXXStatusCode(t *testing.T) {
+ badCodes := []int{
+ -100, 0, 99, 1000, 20000,
+ }
+ for _, badCode := range badCodes {
+ badCode := badCode
+ t.Run(fmt.Sprintf("Code=%d", badCode), func(t *testing.T) {
+ defer func() {
+ if r := recover(); r == nil {
+ t.Fatal("Expected a panic")
+ }
+ }()
+
+ handler := func(rw http.ResponseWriter, _ *http.Request) {
+ rw.WriteHeader(badCode)
+ }
+ r, _ := http.NewRequest("GET", "http://example.org/", nil)
+ rw := NewRecorder()
+ handler(rw, r)
+ })
+ }
+}