-
-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix: adding chartset to the response #7
Conversation
WalkthroughThe changes made in this pull request involve an update to the Changes
Assessment against linked issues
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (2)
response.go (2)
Line range hint
52-78
: Fix multiple header writes and inconsistent error handlingThere are several issues in the response handling flow:
WriteHeader
is called twice (lines 52 and 71), but only the first call has any effect- In the error case,
http.Error
is called afterWriteHeader
, which is incorrect- Error handling uses
http.Error
while success path uses buffer, leading to inconsistent behaviorHere's the suggested fix:
func SendResponse[T any](w http.ResponseWriter, code int, data T, errs []Error, meta *Meta) { w.Header().Set("Content-Type", "application/json; charset=utf-8") response := &Response[T]{ Data: data, Errors: errs, Meta: meta, } - // Set the status code after encoding to ensure no issues with writing the response body - w.WriteHeader(code) - // Attempt to encode the response as JSON var buffer bytes.Buffer if err := json.NewEncoder(&buffer).Encode(response); err != nil { log.Printf("Error writing response: %v", err) - errResponse := `{"errors":[{"code":500,"message":"Internal Server Error"}]}` - http.Error(w, errResponse, http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(&Response[T]{ + Errors: []Error{{ + Code: http.StatusInternalServerError, + Message: "Internal Server Error", + }}, + }) return } // Set the status code after success encoding w.WriteHeader(code) // Write the encoded response to the ResponseWriter if _, err := w.Write(buffer.Bytes()); err != nil { log.Printf("Error writing response: %v", err) + // Note: Cannot change status code here as headers are already sent } }This change:
- Removes the redundant
WriteHeader
call- Makes error handling consistent with the success path by using the same Response structure
- Sets status code before writing the response body
Line range hint
75-77
: Consider improving error handling for write operationsThe current implementation only logs write errors but can't properly handle them since headers are already sent. Consider adding monitoring or metrics for these errors to track potential issues.
if _, err := w.Write(buffer.Bytes()); err != nil { - log.Printf("Error writing response: %v", err) + // Consider using your application's metrics/monitoring system + log.Printf("Failed to write response body (status=%d): %v", code, err) + metrics.IncCounter("response_write_errors") }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
response.go
(1 hunks)
🔇 Additional comments (1)
response.go (1)
52-52
: LGTM! Charset addition meets the requirements.
The Content-Type header now correctly includes the UTF-8 charset specification as required.
Let's verify there are no other Content-Type headers that need similar updates:
✅ Verification successful
Content-Type headers in test files don't require charset updates
The search results show that all other occurrences of Content-Type: application/json
headers are in test files (request_test.go
). Test files typically don't require charset specifications as they're just simulating HTTP requests for testing purposes. The actual response header in response.go
has been correctly updated.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for other Content-Type header settings that might need the charset
rg -i "content-type.*application/json" --type go
Length of output: 561
c8d80ba
to
42dfb07
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (1)
response_test.go (1)
Line range hint
17-43
: Consider enhancing test case names for better clarity.While the test cases are well-structured, consider making the test names even more descriptive by including the expected outcome in the name. For example:
- name: "200 OK with TestResponse body", + name: "should return 200 OK with JSON response when given valid TestResponse",This makes it clearer what the test is verifying and what behavior to expect.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
response.go
(2 hunks)response_test.go
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- response.go
🔇 Additional comments (2)
response_test.go (2)
Line range hint 16-65
: LGTM! Comprehensive test coverage.
The test cases effectively cover various scenarios including:
- Success responses with different payload types
- Error responses with different status codes
- Responses with pagination metadata
- Multiple error messages
70-70
: LGTM! Content-Type header assertion correctly updated.
The assertion now properly validates the charset specification in the Content-Type header, aligning with the PR objective and the solution proposed in issue #5.
Let's verify that this is the only place where Content-Type assertions need to be updated:
✅ Verification successful
Content-Type header assertions are correctly scoped
The Content-Type assertions in request_test.go
are for setting request headers in test setup, not for validating response headers. The original review comment correctly focused on the response header assertion in response_test.go
. No additional changes are needed.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for other Content-Type header assertions that might need updating
rg -l "application/json\"" --type go
Length of output: 53
Script:
#!/bin/bash
# Check the content of request_test.go for Content-Type assertions
rg "Content-Type.*application/json" request_test.go -B 2 -A 2
Length of output: 1249
This PR adds the chatset as utf-8 to all responses.
Closes #5
Summary by CodeRabbit
Content-Type
header in HTTP responses to include character encoding, improving compatibility for clients interpreting JSON data.