From 95bf247ab11b56a0f19b38c92a1123096922688c Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Thu, 10 Apr 2025 16:04:48 +0800 Subject: [PATCH] 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. --- core/controllers/base.go | 1 - core/controllers/utils.go | 25 +++++++++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/core/controllers/base.go b/core/controllers/base.go index d14587f0..3cbe90bf 100644 --- a/core/controllers/base.go +++ b/core/controllers/base.go @@ -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"` diff --git a/core/controllers/utils.go b/core/controllers/utils.go index 287ff876..2925197d 100644 --- a/core/controllers/utils.go +++ b/core/controllers/utils.go @@ -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 {