-
-
Notifications
You must be signed in to change notification settings - Fork 1
(feat) improving response format #2
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| .idea |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,53 +1,80 @@ | ||
| package httpsuite | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "log" | ||
| "net/http" | ||
| ) | ||
|
|
||
| // Response represents the structure of an HTTP response, including a status code, message, and optional body. | ||
| // T represents the type of the `Data` field, allowing this structure to be used flexibly across different endpoints. | ||
| type Response[T any] struct { | ||
| Code int `json:"code"` | ||
| Message string `json:"message"` | ||
| Body T `json:"body,omitempty"` | ||
| Data T `json:"data,omitempty"` | ||
| Errors []Error `json:"errors,omitempty"` | ||
| Meta *Meta `json:"meta,omitempty"` | ||
| } | ||
|
|
||
| // Marshal serializes the Response struct into a JSON byte slice. | ||
| // It logs an error if marshalling fails. | ||
| func (r *Response[T]) Marshal() []byte { | ||
| jsonResponse, err := json.Marshal(r) | ||
| if err != nil { | ||
| log.Printf("failed to marshal response: %v", err) | ||
| } | ||
| // Error represents an error in the aPI response, with a structured format to describe issues in a consistent manner. | ||
| type Error struct { | ||
| // Code unique error code or HTTP status code for categorizing the error | ||
| Code int `json:"code"` | ||
| // Message user-friendly message describing the error. | ||
| Message string `json:"message"` | ||
| // Details additional details about the error, often used for validation errors. | ||
| Details interface{} `json:"details,omitempty"` | ||
| } | ||
|
|
||
| return jsonResponse | ||
| // Meta provides additional information about the response, such as pagination details. | ||
| // This is particularly useful for endpoints returning lists of data. | ||
| type Meta struct { | ||
| // Page the current page number | ||
| Page int `json:"page,omitempty"` | ||
| // PageSize the number of items per page | ||
| PageSize int `json:"page_size,omitempty"` | ||
| // TotalPages the total number of pages available. | ||
| TotalPages int `json:"total_pages,omitempty"` | ||
| // TotalItems the total number of items across all pages. | ||
| TotalItems int `json:"total_items,omitempty"` | ||
| } | ||
|
|
||
| // SendResponse creates a Response struct, serializes it to JSON, and writes it to the provided http.ResponseWriter. | ||
| // If the body parameter is non-nil, it will be included in the response body. | ||
| func SendResponse[T any](w http.ResponseWriter, message string, code int, body *T) { | ||
| // SendResponse sends a JSON response to the client, using a unified structure for both success and error responses. | ||
| // T represents the type of the `data` payload. This function automatically adapts the response structure | ||
| // based on whether `data` or `errors` is provided, promoting a consistent API format. | ||
| // | ||
| // Parameters: | ||
| // - w: The http.ResponseWriter to send the response. | ||
| // - code: HTTP status code to indicate success or failure. | ||
| // - data: The main payload of the response. Use `nil` for error responses. | ||
| // - errs: A slice of Error structs to describe issues. Use `nil` for successful responses. | ||
| // - meta: Optional metadata, such as pagination information. Use `nil` if not needed. | ||
| func SendResponse[T any](w http.ResponseWriter, code int, data T, errs []Error, meta *Meta) { | ||
| w.Header().Set("Content-Type", "application/json") | ||
|
|
||
| response := &Response[T]{ | ||
| Code: code, | ||
| Message: message, | ||
| } | ||
| if body != nil { | ||
| response.Body = *body | ||
| Data: data, | ||
| Errors: errs, | ||
| Meta: meta, | ||
| } | ||
|
|
||
| writeResponse[T](w, response) | ||
| } | ||
| // 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) | ||
|
|
||
| // writeResponse serializes a Response and writes it to the http.ResponseWriter with appropriate headers. | ||
| // If an error occurs during the write, it logs the error and sends a 500 Internal Server Error response. | ||
| func writeResponse[T any](w http.ResponseWriter, r *Response[T]) { | ||
| jsonResponse := r.Marshal() | ||
| errResponse := `{"errors":[{"code":500,"message":"Internal Server Error"}]}` | ||
| http.Error(w, errResponse, http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| w.Header().Set("Content-Type", "application/json") | ||
| w.WriteHeader(r.Code) | ||
| // Set the status code after success encoding | ||
| w.WriteHeader(code) | ||
|
|
||
| if _, err := w.Write(jsonResponse); err != nil { | ||
| // Write the encoded response to the ResponseWriter | ||
| if _, err := w.Write(buffer.Bytes()); err != nil { | ||
| log.Printf("Error writing response: %v", err) | ||
| http.Error(w, "Internal Server Error", http.StatusInternalServerError) | ||
| } | ||
| } |
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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.