Skip to content

Commit

Permalink
Modify SetCode to not panic if it's called after the response was alr…
Browse files Browse the repository at this point in the history
…eady written
  • Loading branch information
Mara Mihali committed Oct 20, 2020
1 parent 30fe423 commit aeb4152
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
8 changes: 4 additions & 4 deletions safehttp/response_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,9 @@ func (w *ResponseWriter) SetCookie(c *Cookie) error {
return w.header.addCookie(c)
}

// SetCode allows setting a response status. This method will panic if an
// invalid status code is passed (i.e. not in the range 1XX-5XX) or if the
// response has already been written.
// SetCode allows setting a response status. If the response was already
// written, trying to set the status code will have no effect. This method will
// panic if an invalid status code is passed (i.e. not in the range 1XX-5XX).
//
// If SetCode was called before NoContent, Redirect or WriteError, the status
// code set by the latter will be the actual response status.
Expand All @@ -174,7 +174,7 @@ func (w *ResponseWriter) SetCookie(c *Cookie) error {
// code passed is either 3XX (redirect) or 4XX-5XX (client/server error).
func (w *ResponseWriter) SetCode(code StatusCode) {
if w.written {
panic("ResponseWriter was already written to")
return
}
if code < 100 || code >= 600 {
panic("invalid status code")
Expand Down
15 changes: 8 additions & 7 deletions safehttp/response_writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,14 @@ func TestResponseWriterStatusCode(t *testing.T) {
},
wantStatus: safehttp.StatusPartialContent,
},
{
name: "Status code set after Write",
write: func(w *safehttp.ResponseWriter) {
w.Write(safehtml.HTMLEscaped("<h1>Escaped, so not really a heading</h1>"))
w.SetCode(safehttp.StatusPartialContent)
},
wantStatus: safehttp.StatusOK,
},
{
name: "SetCode then NoContent",
write: func(w *safehttp.ResponseWriter) {
Expand Down Expand Up @@ -222,13 +230,6 @@ func TestResponseWriterInvalidStatusCode(t *testing.T) {
w.Write(safehtml.HTMLEscaped("<h1>Escaped, so not really a heading</h1>"))
},
},
{
name: "Status code set after write",
write: func(w *safehttp.ResponseWriter) {
w.Write(safehtml.HTMLEscaped("<h1>Escaped, so not really a heading</h1>"))
w.SetCode(safehttp.StatusPartialContent)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit aeb4152

Please sign in to comment.