fix: prevent superfluous response.WriteHeader call in EncodeJSONResponse#536
Open
Kubudak90 wants to merge 1 commit into
Open
fix: prevent superfluous response.WriteHeader call in EncodeJSONResponse#536Kubudak90 wants to merge 1 commit into
Kubudak90 wants to merge 1 commit into
Conversation
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
🟡 Heimdall Review Status
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #407
Problem
EncodeJSONResponsewas callingw.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:This occurred during high-concurrency operations when JSON encoding occasionally failed.
Solution
Encode JSON to a
bytes.Bufferfirst to validate it before writing any headers. Only write the status header after successful encoding. This ensures headers are written exactly once.Changes
bytes.Bufferfirst to catch encoding errorshttp.Erroron encoding failure (maintains JSON content type)routervariable tomuxRouterto avoid shadowing the importTesting
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.