可参考文档:
1.https://github.com/swaggo/gin-swagger gin-swagger官方文档
2.https://github.com/Voyager-ZT/swag
3.https://swagger.io/docs/ Swagger官方文档
4.https://github.com/swaggo
5.https://swaggo.github.io/swaggo.io/declarative_comments_format/general_api_info.html
gin-swagger安装
go get -u github.com/swaggo/swag/cmd/swag
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/gin-swagger/swaggerFiles
将生成的swag.exe文件复制到$GOROOT/bin下
gin-swagger使用
生成swag文档
1.在router生成处添加 router.GET("/docs/*any",ginSwagger.WrapHandler(swaggerFiles.Handler))
2.编写swagger文档
在main函数处:
// @title Go-site Example API
// @version 1.0
// @host IP:port
//@BasePath /kfb/custom_platform_search
func main(){
...
}
在函数处:
// @登录
// @Description login
// @Param username formData string true "username"
// @Param passwd formData string true "passwd"
// @Success 200 {string} string "ok"
// @Router /login [post]
func login(c *gin.Context){
username := c.PostForm("username")
passwd,_ := c.GetPostForm("passwd")
c.String(http.StatusOK, "Hello world "+username+"_"+passwd)
}
其中param: Parameters that separated by spaces. param name
,param type
,data type
,is mandatory?
,comment
attribute(optional)
,
Param Type
-
query
-
path
-
header
-
body
-
formData
比如想实现postman中body—form-Data的传参效果,传入MIME类型为multipart/form-data,返回的MIME类型为json
// @Summary 获取所有项目
// @Accept multipart/form-data
// @Produce json
// @Param current_page formData string true "当前页码"
// @Param username formData string true "用户姓名"
// @Success 200 {string} json "{"code": 20000, "flag": true, "message": "获取考试数据成功"}"
// @Router /custom_platform_search/search_all_project [post]
func (k *Kfb_search_router_handller) Search_all_project(ctx *gin.Context) {
}
3.生成swag文件
在main.go文件目录下进入cmd, 执行swag init
如果想自己指定文件名-g和输出目录-o,swag init -g xxxx/xxx.go -o xxx/
,
4.在main文件中导入生成的swag文件包 import _ "xxx/xxx/docs"
5.启动服务
6.浏览器打开
IP:prot +/docs/ (程序中定义的路径)+index.html
测试 try it out 跨域问题
func main(){
router=gin.Default
router.Use(Cors())
}
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
//复杂点的
//c.Header("Access-Control-Allow-Origin", "*")
//c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
//c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
//c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
//c.Header("Access-Control-Allow-Credentials", "true")
//method := c.Request.Method
//if method == "OPTIONS" {
//c.AbortWithStatus(http.StatusNoContent)
//}
c.Next()
}
}
swagger接入postman
1.确定swagger地址
网上有很多教程,比如https://preparedata.blog.csdn.net/article/details/109474260,但是我的好像没有查看spec空间接口项, 我自己试了下应该是:域名(或是IP:端口号)+basePath+调试工具栏中查到的data-url (input框的value)
2.接入postman
打开postman–collections,点击import–Link,输入swagger接口地址,点击continue,完成。
完成后如下图
3.编辑/修改basePath变量
鼠标放"GO-site Example API"那栏,点击右侧三个点,选择Edit
其中Initial value是初始值,current value指当前使用的,更改为baseUrl。