response

package
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 7 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// 通用错误 00xxxx
	CodeSuccess            = 0   // 成功
	CodeFail               = 1   // 通用失败
	CodeUnauthorized       = 401 // 未授权
	CodeForbidden          = 403 // 无权限
	CodeNotFound           = 404 // 资源不存在
	CodeRateLimit          = 429 // 请求过于频繁
	CodeServerError        = 500 // 服务器错误
	CodeServiceUnavailable = 503 // 服务不可用

	// 用户模块错误 01xxxx
	CodeUserNotFound      = 10001 // 用户不存在
	CodeUserAlreadyExists = 10002 // 用户已存在
	CodeUserDisabled      = 10003 // 用户已禁用
	CodePasswordWrong     = 10004 // 密码错误
	CodePasswordWeak      = 10005 // 密码强度不足
	CodePhoneInvalid      = 10006 // 手机号无效
	CodeEmailInvalid      = 10007 // 邮箱无效
	CodeLoginFailed       = 10008 // 登录失败
	CodeTokenExpired      = 10009 // Token 已过期
	CodeTokenInvalid      = 10010 // Token 无效

	// 文件模块错误 02xxxx
	CodeFileNotFound     = 20001 // 文件不存在
	CodeFileTooLarge     = 20002 // 文件过大
	CodeFileTypeInvalid  = 20003 // 文件类型不支持
	CodeFileUploadFailed = 20004 // 文件上传失败

	// 数据模块错误 03xxxx
	CodeDataNotFound      = 30001 // 数据不存在
	CodeDataAlreadyExists = 30002 // 数据已存在
	CodeDataInvalid       = 30003 // 数据无效
	CodeDataConflict      = 30004 // 数据冲突

	// 业务模块错误 04xxxx
	CodeOperationFailed   = 40001 // 操作失败
	CodeOperationTimeout  = 40002 // 操作超时
	CodeBusinessRuleError = 40003 // 业务规则错误
)

业务错误码定义 格式:模块(2位) + 功能(2位) + 错误类型(2位)

约定:

  • CodeSuccess = 0:成功
  • CodeFail = 1:通用失败
  • 其余 framework 内置错误码使用 HTTP 风格(401/403/404/429/500/503)或 5 位业务码段
  • 参数错误等业务化错误码请由业务项目自行定义,框架不再内置 CodeInvalidParams

Variables

View Source
var (
	ErrUnauthorized       = NewError(CodeUnauthorized, "请先登录")
	ErrForbidden          = NewError(CodeForbidden, "无权限访问")
	ErrNotFound           = NewError(CodeNotFound, "资源不存在")
	ErrRateLimit          = NewError(CodeRateLimit, "请求过于频繁")
	ErrServerError        = NewError(CodeServerError, "服务器错误")
	ErrServiceUnavailable = NewError(CodeServiceUnavailable, "服务暂时不可用")

	// 用户相关
	ErrUserNotFound      = NewError(CodeUserNotFound, "用户不存在")
	ErrUserAlreadyExists = NewError(CodeUserAlreadyExists, "用户已存在")
	ErrUserDisabled      = NewError(CodeUserDisabled, "用户已禁用")
	ErrPasswordWrong     = NewError(CodePasswordWrong, "密码错误")
	ErrPasswordWeak      = NewError(CodePasswordWeak, "密码强度不足")
	ErrPhoneInvalid      = NewError(CodePhoneInvalid, "手机号无效")
	ErrEmailInvalid      = NewError(CodeEmailInvalid, "邮箱无效")
	ErrLoginFailed       = NewError(CodeLoginFailed, "登录失败")
	ErrTokenExpired      = NewError(CodeTokenExpired, "登录已过期")
	ErrTokenInvalid      = NewError(CodeTokenInvalid, "Token 无效")

	// 文件相关
	ErrFileNotFound     = NewError(CodeFileNotFound, "文件不存在")
	ErrFileTooLarge     = NewError(CodeFileTooLarge, "文件过大")
	ErrFileTypeInvalid  = NewError(CodeFileTypeInvalid, "文件类型不支持")
	ErrFileUploadFailed = NewError(CodeFileUploadFailed, "文件上传失败")

	// 数据相关
	ErrDataNotFound      = NewError(CodeDataNotFound, "数据不存在")
	ErrDataAlreadyExists = NewError(CodeDataAlreadyExists, "数据已存在")
	ErrDataInvalid       = NewError(CodeDataInvalid, "数据无效")
	ErrDataConflict      = NewError(CodeDataConflict, "数据冲突")

	// 业务相关
	ErrOperationFailed  = NewError(CodeOperationFailed, "操作失败")
	ErrOperationTimeout = NewError(CodeOperationTimeout, "操作超时")
	ErrBusinessRule     = NewError(CodeBusinessRuleError, "业务规则错误")
)

预定义错误

Functions

func Custom added in v1.1.0

func Custom(c *gin.Context, httpStatus, code int, msg string, data any)

Custom 显式指定 HTTP status 与业务码的响应,不受 Mode 影响。 适用于需要精确控制 HTTP status 的场景(如 REST 模式下的特殊端点)。

func Download

func Download(c *gin.Context, filename string, data []byte)

Download 文件下载响应 Compatibility note: for large files or object-storage streams, prefer DownloadReader so the whole object is not buffered in []byte first.

func DownloadReader added in v1.3.0

func DownloadReader(c *gin.Context, filename, contentType string, contentLength int64, r io.Reader)

DownloadReader 流式下载响应。

对大文件/对象存储下载优先使用此函数,避免先把完整内容读入 []byte 驻留内存。 contentLength 传 -1 表示未知长度;Gin 会省略 Content-Length。

func DownloadWithContentType

func DownloadWithContentType(c *gin.Context, filename string, contentType string, data []byte)

DownloadWithContentType 文件下载(自定义Content-Type)

func Fail

func Fail(c *gin.Context, msg string)

Fail 失败响应

func FailWithCode

func FailWithCode(c *gin.Context, code int, msg string)

FailWithCode 失败响应(自定义错误码)

func FailWithDetail

func FailWithDetail(c *gin.Context, err *Error, detail string)

FailWithDetail 使用预定义错误并添加详细信息。 P1 #15:detail 仅在 detailExposed()(默认 true;App 生产环境置 false)时输出给客户端。

func FailWithError

func FailWithError(c *gin.Context, err *Error)

FailWithError 使用预定义错误响应(M7 修复:通过 ToResponse 保留 Detail)。

func HTML

func HTML(c *gin.Context, data string)

HTML HTML内容响应 Security note: HTML writes raw markup and does not escape untrusted input.

func NotFound

func NotFound(c *gin.Context, msg string)

NotFound 资源不存在响应

func Page

func Page(c *gin.Context, items any, total int64, page, pageSize int)

Page 分页响应

func RateLimit

func RateLimit(c *gin.Context)

RateLimit 请求过于频繁响应

func Redirect

func Redirect(c *gin.Context, code int, url string)

Redirect 页面跳转

func ServerError

func ServerError(c *gin.Context, msg string)

ServerError 服务器错误响应

func SetExposeDetail added in v1.2.0

func SetExposeDetail(expose bool)

SetExposeDetail 设置是否向客户端暴露 Error.Detail(P1 #15)。 生产环境建议置为 false,防止内部错误细节泄露。并发安全。

func SetMode added in v1.1.0

func SetMode(m Mode)

SetMode 设置全局响应模式。

func Success

func Success(c *gin.Context, data any)

Success 成功响应

func SuccessWithMsg

func SuccessWithMsg(c *gin.Context, msg string, data any)

SuccessWithMsg 成功响应(自定义消息)

func Unauthorized

func Unauthorized(c *gin.Context, msg string)

Unauthorized 未授权响应

Types

type Error

type Error struct {
	Code    int    // 错误码
	Message string // 错误消息
	Detail  string // 详细信息(可选)
}

Error 业务错误

func NewError

func NewError(code int, message string) *Error

NewError 创建业务错误

func NewErrorWithDetail

func NewErrorWithDetail(code int, message, detail string) *Error

NewErrorWithDetail 创建带详细信息的业务错误

func (*Error) Error

func (e *Error) Error() string

Error 实现 error 接口

func (*Error) ToResponse

func (e *Error) ToResponse() Response

ToResponse 转换为响应结构。 把 Detail 放入 data.detail(若非空),保留链路细节(M7:原实现丢 Detail)。 P1 #15:仅当 detailExposed()(默认 true;App 生产环境置 false)时才向客户端输出 Detail, 避免内部错误细节在生产泄露。

func (*Error) WithDetail

func (e *Error) WithDetail(detail string) *Error

WithDetail 添加详细信息。

H-10 修复:返回新 *Error 拷贝,不 mutate 接收者。预定义 Err*(如 ErrNotFound)是 包级共享指针,原实现 e.Detail = detail 会污染全局且并发调用存在数据竞争。

nil 接收者:返回 &Error{Detail: detail}(Code=0/Message=""),不 panic;调用方应避免 在 nil 上调用本方法以拿到无 Code/Message 的半成品错误。

type Mode added in v1.1.0

type Mode int32

Mode 响应模式

const (
	// ModeBusiness 业务码模式(默认):所有响应 HTTP 200,错误信息通过 body 中的 code 表达。
	// 兼容存量"业务码 in body"玩法。
	ModeBusiness Mode = iota
	// ModeREST REST 模式:失败响应按业务码映射对应的 HTTP status(401/404/500...),
	// body 仍带业务码。便于 APM / Prometheus / 网关 / Sentry 按 status 区分异常。
	ModeREST
)

func GetMode added in v1.1.0

func GetMode() Mode

GetMode 返回当前响应模式。

type PageData

type PageData struct {
	Items    any   `json:"items"`
	Total    int64 `json:"total"`
	Page     int   `json:"page"`
	PageSize int   `json:"page_size"`
}

PageData 分页数据结构

type Response

type Response struct {
	Code      int    `json:"code"`
	Msg       string `json:"msg"`
	Data      any    `json:"data"`
	RequestID string `json:"request_id"` // 请求追踪ID
}

Response 统一响应结构

M-38/M-39 修复(breaking):Data/RequestID 去掉 omitempty,让 data 与 request_id 字段在所有响应中恒存在(失败时 data=null、未装 RequestID 中间件时 request_id="")。 原实现用 omitempty 导致失败响应无 data 字段、空切片被 omit、未装中间件时无 request_id, 破坏"统一响应结构"契约,下游严格按 schema 解析会出错。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL