47 lines
1.2 KiB
Go
47 lines
1.2 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),
|
||
})
|
||
}
|
||
|
||
// Error 返回错误响应
|
||
func Error(c *fiber.Ctx, httpStatus int, code int, message string) error {
|
||
return c.Status(httpStatus).JSON(Response{
|
||
Code: code,
|
||
Data: nil,
|
||
Message: message,
|
||
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),
|
||
})
|
||
}
|