-
-
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
(feat) improving response format #2
Conversation
b5accdb
to
a14152e
Compare
Caution Review failedThe pull request is closed. WalkthroughThe changes in this pull request involve modifications to the project's response structure, enhancing error handling and introducing metadata support. The Changes
Assessment against linked issues
Poem
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: 5
🧹 Outside diff range and nitpick comments (11)
examples/main.go (2)
38-38
: Enhance example to demonstrate new response featuresThis example could better showcase the new response structure features mentioned in the PR objectives, such as metadata and error handling.
Consider adding examples that demonstrate:
- Using the meta field for pagination
- Handling multiple errors
- Setting custom headers and cookies
Here's a suggested enhancement:
+ // Example with metadata and headers + meta := httpsuite.Meta{ + Pagination: &httpsuite.Pagination{ + Total: 100, + Page: 1, + Limit: 10, + }, + } + headers := http.Header{} + headers.Set("X-Custom-Header", "example") + cookie := &http.Cookie{Name: "session", Value: "example"} - httpsuite.SendResponse[SampleRequest](w, http.StatusOK, *req, nil, nil) + httpsuite.SendResponse[SampleRequest](w, http.StatusOK, *req, headers, cookie)
Line range hint
1-41
: Add documentation for the example usageAs this is an example file demonstrating the new response format, it would be helpful to add comments explaining the new response structure and its features.
Add documentation at the top of the file explaining:
- The purpose of this example
- The response structure (data, errors, meta)
- Available options for headers and cookies
- Common usage patterns
package main +// This example demonstrates the usage of httpsuite's enhanced response format. +// The response structure includes: +// - data: The main payload (typed using generics) +// - errors: Array of error information (when applicable) +// - meta: Additional metadata like pagination +// +// Headers and cookies can be optionally provided to SendResponse. +// For error handling examples, see error_example.gorequest.go (4)
33-34
: Include JSON parsing details in the error messageWhile the error structure is good, consider including the actual parsing error details to help API consumers debug their requests more effectively.
-SendResponse[any](w, http.StatusBadRequest, nil, - []Error{{Code: http.StatusBadRequest, Message: "Invalid JSON format"}}, nil) +SendResponse[any](w, http.StatusBadRequest, nil, + []Error{{Code: http.StatusBadRequest, Message: "Invalid JSON format", Details: err.Error()}}, nil)
48-49
: Consider collecting all missing parameters before respondingCurrently, the function returns on the first missing parameter. For better UX, consider collecting all missing parameters and returning them in a single response.
+var missingParams []Error for _, key := range pathParams { value := chi.URLParam(r, key) if value == "" { - SendResponse[any](w, http.StatusBadRequest, nil, - []Error{{Code: http.StatusBadRequest, Message: "Parameter " + key + " not found in request"}}, nil) - return empty, errors.New("missing parameter: " + key) + missingParams = append(missingParams, Error{ + Code: http.StatusBadRequest, + Message: "Parameter " + key + " not found in request", + }) + continue } // ... rest of the code } +if len(missingParams) > 0 { + SendResponse[any](w, http.StatusBadRequest, nil, missingParams, nil) + return empty, errors.New("missing parameters") +}
62-63
: Improve error message specificityThe error message "validation error" is quite generic. Consider making it more specific or including a summary of the validation failures.
-return empty, errors.New("validation error") +return empty, fmt.Errorf("request validation failed: %v", validationErr)
Line range hint
33-63
: Well-structured error handling implementationThe new error response format is consistently implemented across all error cases and aligns well with REST API best practices. The structured format with
Code
,Message
, andDetails
provides clear and actionable error information.A few architectural considerations:
- The error responses are now more verbose but more informative
- The structure allows for future extension (e.g., adding error codes, localization)
- The implementation maintains backward compatibility while improving error reporting
Consider adding constants for common error messages to maintain consistency and enable easier updates/translations in the future.
response.go (5)
17-17
: Correct the typo in the comment for theError
struct.There's a typo in the comment: "aPI" should be "API".
[typo]
20-24
: Improve field documentation in theError
struct for clarity.Consider revising the comments for the fields in the
Error
struct to enhance clarity and readability. Adding proper punctuation and ensuring consistency can improve maintainability.Apply this diff to update the comments:
type Error struct { - // Code unique error code or HTTP status code for categorizing the error + // Code is a unique error code or HTTP status code for categorizing the error. Code int `json:"code"` - // Message user-friendly message describing the error. + // Message is a user-friendly message describing the error. Message string `json:"message"` - // Details additional details about the error, often used for validation errors. + // Details provides additional information about the error, often used for validation errors. Details interface{} `json:"details,omitempty"` }
59-60
: Align the comment with the code regarding theWriteHeader
call.The comment suggests setting the status code after encoding, but the
w.WriteHeader(code)
call is placed before encoding the response. To prevent confusion, update the comment to reflect the actual order.Apply this diff to correct the comment:
- // Set the status code after encoding to ensure no issues with writing the response body + // Set the status code before encoding the response
24-24
: Consider specifying the type forDetails
to enhance type safety.Using
interface{}
for theDetails
field allows any type, which might lead to inconsistent error details. Consider defining a specific type or usingmap[string]interface{}
to provide structure to the error details.Example:
- Details interface{} `json:"details,omitempty"` + Details map[string]interface{} `json:"details,omitempty"`
47-49
: Clarify parameter usage in theSendResponse
function documentation.The function documentation mentions using
nil
fordata
orerrs
, but sincedata
is of a generic typeT
, passingnil
may not be appropriate for all types. Similarly, clarify how to handle empty slices forerrs
.Consider updating the comments:
// - data: The main payload of the response. Use the zero value of T for error responses. - // - errs: A slice of Error structs to describe issues. Use `nil` for successful responses. + // - errs: A slice of Error structs to describe issues. Use an empty slice or `nil` for successful responses.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (9)
.gitignore
(1 hunks).idea/.gitignore
(0 hunks).idea/httpsuite.iml
(0 hunks).idea/modules.xml
(0 hunks).idea/vcs.xml
(0 hunks)examples/main.go
(1 hunks)request.go
(2 hunks)response.go
(1 hunks)response_test.go
(1 hunks)
💤 Files with no reviewable changes (4)
- .idea/.gitignore
- .idea/httpsuite.iml
- .idea/modules.xml
- .idea/vcs.xml
✅ Files skipped from review due to trivial changes (1)
- .gitignore
🔇 Additional comments (2)
response_test.go (2)
18-21
: LGTM! Test structure aligns well with REST API best practices
The new test struct fields (data
, errs
, meta
) perfectly match the PR objectives for implementing a standardized response format. The use of any
for data provides good flexibility, and making meta
a pointer allows for optional metadata.
54-56
: LGTM! Comprehensive test assertions
The assertions effectively verify all aspects of the response:
- HTTP status code
- Content-Type header
- JSON body structure and values
Closes #1
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Chores
.idea
directory to.gitignore
to prevent IDE-specific files from being tracked.