Files
junhong_cmp_fiber/pkg/response/response.go

47 lines
1.2 KiB
Go
Raw 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 {
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),
})
}