Gin框架Response封装Live Template

Gin框架Response封装Live Template

模板配置

  1. 打开Goland设置 File > Settings > Editor > Live Templates
  2. 新建Go模板组 GinResponse
  3. 添加模板缩写 ginresp

模板内容

package $package$

import (
    "github.com/gin-gonic/gin"
    "github.com/pkg/errors"
    "net/http"
)

// 错误码定义
const (
    CodeSuccess       uint32 = 200
    CodeServerError   uint32 = 100001
    CodeParamError    uint32 = 100002
    CodeUnauthorized  uint32 = 100003
    CodeNotFound      uint32 = 100004
)

// 响应结构体定义
type ResponseSuccess struct {
    Code uint32      `json:"code"`
    Msg  string      `json:"msg"`
    Data interface{} `json:"data,omitempty"`
    Pagination *Pagination `json:"pagination,omitempty"`
}

type ResponseError struct {
    Code uint32 `json:"code"`
    Msg  string `json:"msg"`
}

type Pagination struct {
    Page     int `json:"page"`
    PageSize int `json:"page_size"`
    Total    int `json:"total"`
}

// 成功响应
func Success(c *gin.Context, data interface{}) {
    res := &ResponseSuccess{
        Code: CodeSuccess,
        Msg:  "操作成功",
        Data: data,
    }
    c.JSON(http.StatusOK, res)
    c.Abort()
}

// 带分页的成功响应
func SuccessWithPage(c *gin.Context, data interface{}, page, pageSize, total int) {
    res := &ResponseSuccess{
        Code: CodeSuccess,
        Msg:  "操作成功",
        Data: data,
        Pagination: &Pagination{
            Page:     page,
            PageSize: pageSize,
            Total:    total,
        },
    }
    c.JSON(http.StatusOK, res)
    c.Abort()
}

// 错误响应
func Error(c *gin.Context, code uint32, err error) {
    errMsg := err.Error()
    res := &ResponseError{
        Code: code,
        Msg:  errMsg,
    }
    c.JSON(http.StatusOK, res)
    c.Abort()
}

// 参数错误响应
func ErrorParam(c *gin.Context, err error) {
    Error(c, CodeParamError, errors.Wrap(err, "参数错误"))
}

// 服务器错误响应
func ErrorServer(c *gin.Context, err error) {
    Error(c, CodeServerError, errors.Wrap(err, "服务器内部错误"))
}
$END$

模板变量配置

变量名 表达式 默认值
package className() response
Data suggestVariableName() data

使用方法

  1. 在Go文件中输入 ginresp
  2. 按Tab键展开模板
  3. 根据需要修改包名和变量名

依赖安装

go get github.com/gin-gonic/gin
go get github.com/pkg/errors

使用示例

// 基本成功响应
func ListHandler(c *gin.Context) {
    data := []string{"item1", "item2"}
    Success(c, data)
}

// 带分页的成功响应
func PageHandler(c *gin.Context) {
    data := []string{"item1", "item2"}
    SuccessWithPage(c, data, 1, 10, 100)
}

// 错误响应
func CreateHandler(c *gin.Context) {
    var req Req
    if err := c.ShouldBindJSON(&req); err != nil {
        ErrorParam(c, err)
        return
    }
    // 业务逻辑...
    Success(c, nil)
}
阅读: 57 | 发布时间: 2025-07-06 18:55:23