Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
60 lines
1.5 KiB
Go
60 lines
1.5 KiB
Go
package response
|
||
|
||
import (
|
||
"time"
|
||
|
||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||
"github.com/gofiber/fiber/v2"
|
||
)
|
||
|
||
// Response 统一 API 响应结构
|
||
type Response struct {
|
||
Code int `json:"code"` // 应用错误码(0 = 成功)
|
||
Data any `json:"data"` // 响应数据(对象、数组或 null)
|
||
Message string `json:"msg"` // 可读消息
|
||
Timestamp string `json:"timestamp"` // ISO 8601 时间戳
|
||
}
|
||
|
||
// Success 返回成功响应
|
||
func Success(c *fiber.Ctx, data any) error {
|
||
return c.JSON(Response{
|
||
Code: errors.CodeSuccess,
|
||
Data: data,
|
||
Message: "success",
|
||
Timestamp: time.Now().Format(time.RFC3339),
|
||
})
|
||
}
|
||
|
||
// SuccessWithMessage 返回带自定义消息的成功响应
|
||
func SuccessWithMessage(c *fiber.Ctx, data any, message string) error {
|
||
return c.JSON(Response{
|
||
Code: errors.CodeSuccess,
|
||
Data: data,
|
||
Message: message,
|
||
Timestamp: time.Now().Format(time.RFC3339),
|
||
})
|
||
}
|
||
|
||
// PaginationData 分页数据结构
|
||
type PaginationData struct {
|
||
Items any `json:"items"` // 数据列表
|
||
Total int64 `json:"total"` // 总数
|
||
Page int `json:"page"` // 当前页码
|
||
Size int `json:"size"` // 每页大小
|
||
}
|
||
|
||
// SuccessWithPagination 返回分页响应
|
||
func SuccessWithPagination(c *fiber.Ctx, items any, total int64, page, size int) error {
|
||
return c.JSON(Response{
|
||
Code: errors.CodeSuccess,
|
||
Data: PaginationData{
|
||
Items: items,
|
||
Total: total,
|
||
Page: page,
|
||
Size: size,
|
||
},
|
||
Message: "success",
|
||
Timestamp: time.Now().Format(time.RFC3339),
|
||
})
|
||
}
|