Skip to content

fix: skip body encoding for all no-body HTTP status codes#1310

Open
Yanhu007 wants to merge 1 commit intogo-kit:masterfrom
Yanhu007:fix/encode-json-no-body-status-codes
Open

fix: skip body encoding for all no-body HTTP status codes#1310
Yanhu007 wants to merge 1 commit intogo-kit:masterfrom
Yanhu007:fix/encode-json-no-body-status-codes

Conversation

@Yanhu007
Copy link
Copy Markdown

Fixes #1291

Problem

EncodeJSONResponse only skips body encoding for 204 No Content, but the HTTP specification (RFC 9110 §6.4.1, §15.3.5, §15.4.5) requires no message body for:

  • 1xx (Informational)
  • 204 (No Content)
  • 304 (Not Modified)

When a response implements StatusCoder and returns 304, json.NewEncoder(w).Encode() writes a body, causing net/http to return:

http: request method or response status code does not allow body

Fix

Extend the no-body check to also cover 1xx and 304 status codes:

if code == http.StatusNoContent || code == http.StatusNotModified || (code >= 100 && code < 200) {
    return nil
}

All existing tests pass.

EncodeJSONResponse only skips body encoding for 204 No Content,
but HTTP spec (RFC 9110) requires no message body for 1xx, 204,
and 304 responses. Writing a body for 304 Not Modified causes
net/http to return an error.

Extend the check to skip body encoding for 1xx, 204, and 304.

Fixes go-kit#1291
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

http.EncodeJSONResponse body writing is not compatible with net/http

1 participant