1、安装swagger
$ go get -u github.com/swaggo/swag/cmd/swag # 1.16 or newer $ go install github.com/swaggo/swag/cmd/swag@latest
2、下载gin-swagger
go get -u github.com/swaggo/gin-swagger go get -u github.com/swaggo/files
3、使用gin-swagger
package main
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
"./docs" // docs is generated by Swag CLI, you have to import it.
)
// @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
func main() {
// programmatically set swagger info
docs.SwaggerInfo.Title = "Swagger Example API"
docs.SwaggerInfo.Description = "This is a sample server Petstore server."
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Host = "petstore.swagger.io"
docs.SwaggerInfo.basePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}
r := gin.New()
// use ginSwagger middleware to serve the API docs
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run()
}
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
"github.com/swaggo/swag/example/celler/model"
)
// ShowAccount godoc
// @Summary Show an account
// @Description get string by ID
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [get]
func (c *Controller) ShowAccount(ctx *gin.Context) {
id := ctx.Param("id")
aid, err := strconv.Atoi(id)
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
account, err := model.AccountOne(aid)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, account)
}
// ListAccounts godoc
// @Summary List accounts
// @Description get accounts
// @Tags accounts
// @Accept json
// @Produce json
// @Param q query string false "name search by q" Format(email)
// @Success 200 {array} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
q := ctx.Request.URL.Query().Get("q")
accounts, err := model.AccountsAll(q)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, accounts)
}
//...
4、在根目录下(或者指定目录) 执行
swag init
会在根目录(指定目录) 生成docs文件夹,同时会生成三个配置文件。
5、启动gin 服务
如果非本地机,localhost 改成自己ip,加上端口
http://localhost:/swagger/index.html
附录:
gin学习(五) gin集成swagger文档 | 凡凡时间
object models.Result "成功后返回"
// @Router /issue/add [post]
func IssueAdd(c *gin.Context) {
1
2
3
4
5
6
7
8
9
10
说明:
- Summary是接口说明
- Tags可以将相同tag的放到同一个分组下
- Param就是要请求的参数,数据格式为:参数名称 参数位置 参数类型 是否必须 描述
- 这个里面是一个struct类型的参数 models.Issue
- 这里的参数位置是body, 更多的值参考文末的参考链接
- Success 返回信息 这里返回的是models.Result类型的值
- Router 路由信息,请求方法
#IssueList的注释
// IssueList function
// @Summary issue列表
// @version 1.0
// @Tags issue
// @Success 200 {object} models.Result{data=[]models.Issue} ”成功后返回"
// @Router /issue/list [get]
func IssueList(c *gin.Context) {
var issue models.Issue
issues := issue.List()
c.JSON(200, gin.H{
"stat": 0,
"message": "列出成功",
"data": issues,
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
说明:
- Success这里的返回值是一个嵌套类型的,注意这样的写法
#IssueDelete的注释
// IssueDelete function
// @Summary 删除issue
// @version 1.0
// @Tags issue
// @Accept json
// @Produce json
// @Param data body models.SimpleIssue true "issue id"
// @Success 200 object models.Result "成功后返回"
// @Router /issue/delete [delete]
func IssueDelete(c *gin.Context) {
1
2
3
4
5
6
7
8
9
10
说明:
- 参数位置为body
- 返回值为models.Result类型
#IssueDetail的注释
// IssueDetail function
// @Summary issue详情
// @version 1.0
// @Tags issue
// @Accept json
// @Produce json
// @Param id query int true "issue id"
// @Success 200 {object} models.Result{data=models.Issue} "成功后返回"
// @Router /issue/detail [get]
func IssueDetail(c *gin.Context) {
1
2
3
4
5
6
7
8
9
10
说明:
- 参数位置为query
- Success中返回的是嵌套类型数据
#IssueUpdate的注释
// IssueUpdate function
// @Summary 更新issue
// @version 1.0
// @Tags issue
// @Accept json
// @Produce json
// @Param data body models.Issue true "issue params"
// @Success 200 object models.Result "成功后返回"
// @Router /issue/update [put]
func IssueUpdate(c *gin.Context) {
1
2
3
4
5
6
7
8
9
10
#生成swagger文件
执行下面的命令,如果找不到swag命令,记得将GOPATH的路径也加上, 执行成功后会在项目目录下生产一个docs目录
$ swag init
1
#访问测试
运行服务
$ go run main.go
1
在浏览器中访问下面的地址: http://localhost:8080/swagger/index.html
#效果
#增加token验证方法
-
首先在main上加上下面注释
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
func main() {
1
2
3
4
说明:
- 安全方式选择的是securitydefinitions.apikey 对应的值是ApiKeyAuth
- in 是值token携带的位置,这里是在header中
- name 就是heaer中的名称
-
在所有需要鉴权的接口中增加下面的注释
// @Security ApiKeyAuth
func IssueDetail(c *gin.Context) {
1
2
-
重新swag init, 然后在浏览器中查看,就会看到在页面的右上方就有了一个authorize, 点击就可以设置token的值了
首先在main上加上下面注释
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
func main() {
1
2
3
4
说明:
- 安全方式选择的是securitydefinitions.apikey 对应的值是ApiKeyAuth
- in 是值token携带的位置,这里是在header中
- name 就是heaer中的名称
在所有需要鉴权的接口中增加下面的注释
// @Security ApiKeyAuth
func IssueDetail(c *gin.Context) {
1
2
重新swag init, 然后在浏览器中查看,就会看到在页面的右上方就有了一个authorize, 点击就可以设置token的值了



