Files
portal-mini-go/internal/pkg/response/response.go
T
2026-10-25 20:27:59 +08:00

30 lines
904 B
Go

// Package response 提供统一的 HTTP 响应结构与写入辅助。
// 所有 handler 的成功响应走 OK,错误统一由 ErrorHandler 中间件转换(见 middleware)。
package response
import (
"net/http"
"github.com/gin-gonic/gin"
"portal-mini-go/internal/pkg/errors"
)
// Response 是统一的响应结构。
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data,omitempty"`
}
// OK 写入成功响应(HTTP 200 + 业务码 0)。
func OK(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, Response{Code: 0, Msg: "ok", Data: data})
}
// Error 把业务错误转为统一响应体。通常在 ErrorHandler 中间件中调用;
// 若 handler 内部需要直接返回也可使用。
func Error(c *gin.Context, err error) {
c.JSON(http.StatusOK, Response{Code: errors.CodeOf(err), Msg: errors.MsgOf(err)})
}