Skip to content

fix: prevent superfluous response.WriteHeader call in EncodeJSONResponse#536

Open
Kubudak90 wants to merge 1 commit into
coinbase:masterfrom
Kubudak90:master
Open

fix: prevent superfluous response.WriteHeader call in EncodeJSONResponse#536
Kubudak90 wants to merge 1 commit into
coinbase:masterfrom
Kubudak90:master

Conversation

@Kubudak90

Copy link
Copy Markdown

Fixes #407

Problem

EncodeJSONResponse was calling w.WriteHeader(status) before attempting to encode the JSON. If the JSON encoding failed, http.Error() would try to write the header again, causing the error:

http: superfluous response.WriteHeader call from github.com/coinbase/rosetta-sdk-go/server.EncodeJSONResponse

This occurred during high-concurrency operations when JSON encoding occasionally failed.

Solution

Encode JSON to a bytes.Buffer first to validate it before writing any headers. Only write the status header after successful encoding. This ensures headers are written exactly once.

Changes

  • Encode JSON to bytes.Buffer first to catch encoding errors
  • Only write status header after successful encoding
  • Return JSON error response instead of http.Error on encoding failure (maintains JSON content type)
  • Rename router variable to muxRouter to avoid shadowing the import

Testing

The fix prevents the race condition where headers could be written twice. The buffer approach is a common pattern in Go HTTP handlers to ensure atomic header writes.

Fixes coinbase#407

The bug occurred because EncodeJSONResponse would call w.WriteHeader(status)
before attempting to encode the JSON. If encoding failed, http.Error() would
try to write the header again, causing 'superfluous response.WriteHeader call'.

The fix encodes to a buffer first, only writing headers after successful
encoding. This ensures headers are written exactly once.

Changes:
- Encode JSON to bytes.Buffer first to validate before writing
- Only write status header after successful encoding
- Return JSON error response instead of http.Error on encoding failure
- Rename router variable to muxRouter to avoid shadowing import
@cb-heimdall

Copy link
Copy Markdown

🟡 Heimdall Review Status

Requirement Status More Info
Reviews 🟡 0/1
Denominator calculation
Show calculation
1 if user is bot 0
1 if user is external 0
2 if repo is sensitive 0
From .codeflow.yml 1
Additional review requirements
Show calculation
Max 0
0
From CODEOWNERS 0
Global minimum 0
Max 1
1
1 if commit is unverified 1
Sum 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

EncodeJSONResponse - http: superfluous response.WriteHeader call

2 participants