Go语言使用swagger生成接口文档的方法
swagger介绍
gin-swagger实战
- 按照swagger要求给接口代码添加声明式注释,具体参照声明式注释格式。
- 使用swag工具扫描代码自动生成API接口文档数据
- 使用gin-swagger渲染在线接口文档页面
第一步:添加注释
packagemain
//@title这里写标题
//@version1.0
//@description这里写描述信息
//@termsOfServicehttp://swagger.io/terms/
//@contact.name这里写联系人信息
//@contact.urlhttp://www.swagger.io/support
//@contact.emailsupport@swagger.io
//@license.nameApache2.0
//@license.urlhttp://www.apache.org/licenses/LICENSE-2.0.html
//@host这里写接口服务的host
//@BasePath这里写basepath
funcmain(){
r:=gin.New()
//liwenzhou.com...
r.Run()
}
//GetPostListHandler2升级版帖子列表接口
//@Summary升级版帖子列表接口
//@Description可按社区按时间或分数排序查询帖子列表接口
//@Tags帖子相关接口
//@Acceptapplication/json
//@Produceapplication/json
//@ParamAuthorizationheaderstringfalse"Bearer用户令牌"
//@Paramobjectquerymodels.ParamPostListfalse"查询参数"
//@SecurityApiKeyAuth
//@Success200{object}_ResponsePostList
//@Router/posts2[get]
funcGetPostListHandler2(c*gin.Context){
//GET请求参数(querystring):/api/v1/posts2?page=1&size=10&order=time
//初始化结构体时指定初始参数
p:=&models.ParamPostList{
Page:1,
Size:10,
Order:models.OrderTime,
}
iferr:=c.ShouldBindQuery(p);err!=nil{
zap.L().Error("GetPostListHandler2withinvalidparams",zap.Error(err))
ResponseError(c,CodeInvalidParam)
return
}
data,err:=logic.GetPostListNew(p)
//获取数据
iferr!=nil{
zap.L().Error("logic.GetPostList()failed",zap.Error(err))
ResponseError(c,CodeServerBusy)
return
}
ResponseSuccess(c,data)
//返回响应
}
//bluebell/models/params.go
//ParamPostList获取帖子列表querystring参数
typeParamPostListstruct{
CommunityIDint64`json:"community_id"form:"community_id"`//可以为空
Pageint64`json:"page"form:"page"example:"1"`//页码
Sizeint64`json:"size"form:"size"example:"10"`//每页数据量
Orderstring`json:"order"form:"order"example:"score"`//排序依据
}
//bluebell/controller/docs_models.go
//_ResponsePostList帖子列表接口响应数据
type_ResponsePostListstruct{
CodeResCode`json:"code"`//业务响应状态码
Messagestring`json:"message"`//提示信息
Data[]*models.ApiPostDetail`json:"data"`//数据
}
第二步:生成接口文档数据
goget-ugithub.com/swaggo/swag/cmd/swag
swaginit
./docs ├──docs.go ├──swagger.json └──swagger.yaml
第三步:引入gin-swagger渲染文档数据
import( //liwenzhou.com... _"bluebell/docs"//千万不要忘了导入把你上一步生成的docs gs"github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger/swaggerFiles" "github.com/gin-gonic/gin" )
r.GET("/swagger/*any",gs.WrapHandler(swaggerFiles.Handler))
gin_swagger文档
r.GET("/swagger/*any",gs.DisablingWrapHandler(swaggerFiles.Handler,"NAME_OF_ENV_VARIABLE"))
总结
到此这篇关于Go语言使用swagger生成接口文档的文章就介绍到这了,更多相关Go使用swagger生成接口文档内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。