refactor: enhance response structures and add JSON serialization

- Removed redundant comment for GetListParams struct to improve clarity.
- Updated Response, ListResponse, and VoidResponse types to use omitempty for the Error field, streamlining JSON output.
- Introduced ToJSON method for Response and ListResponse types to facilitate easy serialization of response data.
- Ensured alignment with existing coding standards and improved code maintainability through consistent struct definitions.
This commit is contained in:
Marvin Zhang
2025-04-10 16:04:48 +08:00
parent 3372c9a69b
commit 95bf247ab1
2 changed files with 21 additions and 5 deletions

View File

@@ -61,7 +61,6 @@ type BaseController[T any] struct {
actions []Action
}
// GetListParams represents parameters for GetList with pagination
type GetListParams struct {
Filter string `query:"filter" description:"Filter query"`
Sort string `query:"sort" description:"Sort options"`

View File

@@ -283,13 +283,14 @@ func SortsToOption(sorts []entity.Sort) (sort bson.D, err error) {
type BaseResponse interface {
GetData() interface{}
GetDataString() string
ToJSON() string
}
type Response[T any] struct {
Status string `json:"status"`
Message string `json:"message"`
Data T `json:"data"`
Error string `json:"error"`
Data T `json:"data,omitempty"`
Error string `json:"error,omitempty"`
}
func (r Response[T]) GetData() any {
@@ -304,12 +305,20 @@ func (r Response[T]) GetDataString() string {
return string(data)
}
func (r Response[T]) ToJSON() string {
data, err := json.Marshal(r)
if err != nil {
return ""
}
return string(data)
}
type ListResponse[T any] struct {
Status string `json:"status"`
Message string `json:"message"`
Total int `json:"total"`
Data []T `json:"data"`
Error string `json:"error"`
Error string `json:"error,omitempty"`
}
func (r ListResponse[T]) GetData() any {
@@ -327,10 +336,18 @@ func (r ListResponse[T]) GetDataString() string {
return string(data)
}
func (r ListResponse[T]) ToJSON() string {
data, err := json.Marshal(r)
if err != nil {
return ""
}
return string(data)
}
type VoidResponse struct {
Status string `json:"status"`
Message string `json:"message"`
Error string `json:"error"`
Error string `json:"error,omitempty"`
}
func (r VoidResponse) GetData() any {