Skip to content

Commit

Permalink
Merge pull request #153 from monzo/jacetan/check-status-before-write-…
Browse files Browse the repository at this point in the history
…body

Don't write body for certain status codes
  • Loading branch information
jace-ys authored Jun 8, 2022
2 parents d76c9c6 + 0253ff0 commit 38e4562
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion http.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,20 @@ func copyErrSeverity(err error) slog.Severity {
}
}

// bodyAllowedForStatus reports whether a given response status code
// permits a body. This is taken directly from the net/http package.
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
}

// HttpHandler transforms the given Service into a standard library HTTP handler. It is one of the main "bridges"
// between Typhon and net/http.
func HttpHandler(svc Service) http.Handler {
Expand All @@ -113,7 +127,7 @@ func HttpHandler(svc Service) http.Handler {
rwHeader[k] = v
}
rw.WriteHeader(rsp.StatusCode)
if rsp.Body != nil {
if rsp.Body != nil && bodyAllowedForStatus(rsp.StatusCode) {
defer rsp.Body.Close()
buf := *httpChunkBufPool.Get().(*[]byte)
defer httpChunkBufPool.Put(&buf)
Expand Down

0 comments on commit 38e4562

Please sign in to comment.