# response **Repository Path**: xgo-core/response ## Basic Information - **Project Name**: response - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-06-30 - **Last Updated**: 2026-06-30 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # response `response` 是一个用于 Gin 应用的 JSON 响应辅助包。 它将 HTTP 响应统一为 `Body` 结构: ```json { "code": 0, "msg": "success", "data": {} } ``` ## 安装 ```sh go get gitee.com/xgo-core/response ``` ## 响应结构 ```go type Body struct { Code int64 `json:"code"` Msg string `json:"msg"` Data any `json:"data"` } ``` ## 错误约定 业务错误可以实现 `Error` 接口: ```go type Error interface { Code() int64 Error() string } ``` 当错误实现了该接口时,`Json` 会使用 `Code()` 的返回值作为响应 `code`,并返回 HTTP `200`。 该方法通过 `errors.As` 识别错误,因此也支持被包装过的业务错误: ```go return fmt.Errorf("create user: %w", response.ParamError) ``` ## 使用示例 ```go package main import ( "github.com/gin-gonic/gin" "gitee.com/xgo-core/response" ) func main() { r := gin.Default() r.GET("/ping", func(ctx *gin.Context) { _ = response.Json(ctx, gin.H{"pong": true}, nil) }) r.GET("/bad-request", func(ctx *gin.Context) { _ = response.Json(ctx, nil, response.ParamError) }) _ = r.Run(":8080") } ``` ## 行为说明 | 场景 | HTTP 状态码 | `code` | `msg` | 返回值 | | --- | --- | --- | --- | --- | | `err == nil` | `200` | `0` | `success` | `nil` | | `err` 实现 `response.Error` | `200` | `err.Code()` | `err.Error()` | `err` | | 其他错误 | `500` | `response.UnknownError.Code()` | `err.Error()` | `err` | ## 内置错误 ```go const ( UnknownError response.SystemError = 1 ParamError response.SystemError = 2 ) ``` `SystemError` 已实现 `response.Error` 接口。