gin+gorm HelloWorld(为它加上Swagger)

我就是小政政 · · 878 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

为它加上Swagger

下载golang.org/x相关包
由于这些包需要科学上网才能下载,使用下面方式曲线救国:

mkdir -p $GOPATH/src/github.com/golang/
git clone https://github.com/golang/sys.git $GOPATH/src/github.com/golang/sys
git clone https://github.com/golang/net.git $GOPATH/src/github.com/golang/net
git clone https://github.com/golang/text.git $GOPATH/src/github.com/golang/text
git clone https://github.com/golang/lint.git $GOPATH/src/github.com/golang/lint
git clone https://github.com/golang/tools.git $GOPATH/src/github.com/golang/tools
git clone https://github.com/golang/crypto.git $GOPATH/src/github.com/golang/crypto

mkdir -p $GOPATH/src/golang.org
ln -s $GOPATH/src/github.com/golang $GOPATH/src/golang.org/x

go get -u github.com/swaggo/swag/cmd/swag

验证是否安装成功

swag -v
swag version v1.4.1

安装 gin-swagger

go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/gin-swagger/swaggerFiles

编写API注释

gin-swagger 给出的范例:

// @Summary Add a new pet to the store
// @Description get string by ID
// @Accept  json
// @Produce  json
// @Param   some_id     path    int     true        "Some ID"
// @Success 200 {string} string "ok"
// @Failure 400 {object} web.APIError "We need ID!!"
// @Failure 404 {object} web.APIError "Can not find ID"
// @Router /testapi/get-string-by-int/{some_id} [get]

我们可以参照 Swagger 的注解规范和范例去编写

// @Summary 新增文章标签
// @Produce  json
// @Param name query string true "Name"
// @Param state query int false "State"
// @Param created_by query int false "CreatedBy"
// @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}"
// @Router /api/v1/tags [post]
func AddTag(c *gin.Context) {
// @Summary 修改文章标签
// @Produce  json
// @Param id path int true "ID"
// @Param name query string true "ID"
// @Param state query int false "State"
// @Param modified_by query string true "ModifiedBy"
// @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}"
// @Router /api/v1/tags/{id} [put]
func EditTag(c *gin.Context) {
生成

我们进入到gin-blog的项目根目录中,执行初始化命令
swag init
完毕后会在项目根目录下生成docs

docs/
├── docs.go
└── swagger
    ├── swagger.json
    └── swagger.yaml
效果

to be continued


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:我就是小政政

查看原文:gin+gorm HelloWorld(为它加上Swagger)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

878 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传