-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
(feat) improving response format (#2)
* chore: adds gitignore * feat: better response format * docs: update readme * fix: code review suggestions
- Loading branch information
Showing
10 changed files
with
107 additions
and
157 deletions.
There are no files selected for viewing
This file contains 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 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 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 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 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 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