Files
junhong_cmp_fiber/pkg/response/response.go

66 lines
1.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 {
err := c.JSON(Response{
Code: errors.CodeSuccess,
Data: data,
Message: "success",
Timestamp: time.Now().Format(time.RFC3339),
})
c.Set(fiber.HeaderContentType, "application/json; charset=utf-8")
return err
}
// SuccessWithMessage 返回带自定义消息的成功响应
func SuccessWithMessage(c *fiber.Ctx, data any, message string) error {
err := c.JSON(Response{
Code: errors.CodeSuccess,
Data: data,
Message: message,
Timestamp: time.Now().Format(time.RFC3339),
})
c.Set(fiber.HeaderContentType, "application/json; charset=utf-8")
return err
}
// 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 {
err := c.JSON(Response{
Code: errors.CodeSuccess,
Data: PaginationData{
Items: items,
Total: total,
Page: page,
Size: size,
},
Message: "success",
Timestamp: time.Now().Format(time.RFC3339),
})
c.Set(fiber.HeaderContentType, "application/json; charset=utf-8")
return err
}