在做 API 接口开发时, 一般会统一 API 返回格式, 例如

{
"code": 200,
"data": {
//xxxxx
//xxxxx
},
"message": "OK"
}

在后端代码定义中, 也会定义一个结构体来对应这种结构, 并且, 由于 data 字段里的数据是未知的(与具体业务相关), 所以会定义一个 interface 来接收

type ApiResponse struct {
Code int `json:"code"`
Msg string `json:"message"`
Data interface{} `json:"data"`
}

然后根据具体业务响应, 向 data 传入不同的模型, 比如

c.JSON(200, ApiResponse{200, "OK", User})

但是这里有个很大的问题, swagger 文档中, 这个接口的返回值该怎么定义?

// @Summary 获取用户信息
// ...
// ...
// @Success 200 {object} ApiResponse "ok"
func GetUser(c *gin.Context) {
xxxx
}

如果这样定义, 生成的文档会是下面这样, 因为原始 ApiResponse 就是一个 interface, 所以是空

但是这样的文档写出来就没什么意义了, 大多数的做法就是会专门定义一个用于 swagger 显示的结构体, 类似这样

type UserResponse struct {
Code int `json:"code"`
Msg string `json:"message"`
Data User `json:"data"`
}

虽然效果有了, 但是这样无疑增加了巨多的工作量, 让写代码变得索然无味, 翻看 swaggo/swag 的文档, 发现支持了替换字段的方式, 可以完美解决现在这种问题, 效果如下

下面是测试代码

package main

import (
"net/http"
"strconv" "github.com/gin-gonic/gin"
) // @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/ // @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io // @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host petstore.swagger.io
// @BasePath /v2
func main() {
r := gin.New()
r.GET("/user/:id", GetUser)
} // @Summary 获取用户信息
// @Description get User by ID
// @ID get-user-by-id
// @Accept json
// @Produce json
// @Param id path int true "用户 id"
// @Success 200 {object} ApiResponse{data=User} "ok"
// @Router /user/{id} [get]
func GetUser(c *gin.Context) {
resp := new(ApiResponse) paramID := c.Param("id")
uid, _ := strconv.Atoi(paramID)
user := User{
ID: uid,
Name: "张三",
}
resp.Code = 200
resp.Msg = "OK"
resp.Data = user
c.JSON(http.StatusOK, resp)
} type User struct {
ID int `json:"id"`
Name string `json:"name"`
} type ApiResponse struct {
Code int `json:"code"`
Msg string `json:"message"`
Data interface{} `json:"data"`
}

最新文章

  1. EC笔记,第二部分:10.让=返回指向*this的引用
  2. 【Bugly 技术干货】Android开发必备知识:为什么说Kotlin值得一试
  3. 深入理解javascript---命名函数表达式
  4. Sublime Text 3前端开发常用优秀插件介绍
  5. [SoapUI] JDBC 请求连接SQL Sever,MySQL
  6. truncate有外键约束的表,报ORA-02266处理。
  7. vb.net下载代码
  8. A planning attack on a commuter train carriage in Taipei
  9. 开发一个支持多用户在线的FTP程序
  10. AS3.0面向对象的写法,类和实例
  11. chroot
  12. Django:(博客系统)添加文章(中文)出现UnicodeEncodeError乱码
  13. Scrapy选择器的用法
  14. cocos2dx 3.3 + QT5.3制作游戏编辑器
  15. Linux 安装composer
  16. python环境下使用tab自动补全命令
  17. 深入理解JS中的变量及变量作用域
  18. C#Redis哈希Hashes
  19. iOS编程(双语版) - 视图 - 手工代码(不使用向导)创建视图
  20. 使用kubeadm安装Kubernetes v1.10

热门文章

  1. MS office设置夜间模式
  2. python之字符串,列表,集合,字典方法
  3. [no_code][Alpha]发布声明报告
  4. Canal Server发送binlog消息到Kafka消息队列中
  5. poi实现生成下拉选联动
  6. Noip模拟36 2021.8.11
  7. jzoj6094
  8. STM32中AD采样的三种方法分析
  9. Balance的数学思想构造辅助函数
  10. Python NameError: name 'unicode' is not defined