zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Go --- gin配置swagger

2023-03-14 22:40:00 时间

gin配置swagger


不多说废话,直接开始 准备工作:

  1. 下载swag for go

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

  1. 然后执行

swag init

你就会发现自己的项目中多出一个docs文档文件

  1. 下载 gin-swagger

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

go get -u github.com/swaggo/files

  1. 在你的代码中引入
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files

测试:

测试方法:

// PingExample godoc
// @Summary ping example
// @Schemes
// @Description do ping
// @Tags example
// @Accept json
// @Produce json
// @Success 200 {string} Helloworld
// @Router /example/helloworld [get]
func Helloworld(g *gin.Context)  {
    g.JSON(http.StatusOK,"helloworld")
}

当这个方法存在时,再次使用swag init将会更新文档中的信息

如果要使用这个文档就要先引用

import (
    docs "GinTest/swag/docs"
)

然后再 main.go 中配置swagger

func main()  {
    r := gin.Default()
    docs.SwaggerInfo.Title = "Swagger Example API"
    docs.SwaggerInfo.Description = "This is a sample server Petstore server."
    docs.SwaggerInfo.Version = "1.0"
    docs.SwaggerInfo.Host = "localhost:8080"
    docs.SwaggerInfo.Schemes = []string{"http", "https"}
    docs.SwaggerInfo.BasePath = "/api/v1"
    v1 := r.Group("/api/v1")
    {
        eg := v1.Group("/example")
        {
            eg.GET("/helloworld",Helloworld)
        }
    }
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
    r.Run(":8080")
}

此时的项目结构为

image

启动项目,然后访问

http://localhost:8080/swagger/index.html

这时你就会看到

image

所有代码和命令

需要安装

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

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

go get -u github.com/swaggo/files

需要在代码中导入的

import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
import  docs "GinTest/swag/docs" // your docs

测试代码:

package main
import (
    docs "GinTest/swag/docs"
    "github.com/gin-gonic/gin"
    swaggerfiles "github.com/swaggo/files"
    ginSwagger "github.com/swaggo/gin-swagger"
    "net/http"
)
// @BasePath /api/v1
// PingExample godoc
// @Summary ping example
// @Schemes
// @Description do ping
// @Tags example
// @Accept json
// @Produce json
// @Success 200 {string} Helloworld
// @Router /example/helloworld [get]
func Helloworld(g *gin.Context)  {
    g.JSON(http.StatusOK,"helloworld")
}
func main()  {
    r := gin.Default()
    docs.SwaggerInfo.Title = "Swagger Example API"
    docs.SwaggerInfo.Description = "This is a sample server Petstore server."
    docs.SwaggerInfo.Version = "1.0"
    docs.SwaggerInfo.Host = "localhost:8080"
    docs.SwaggerInfo.Schemes = []string{"http", "https"}
    docs.SwaggerInfo.BasePath = "/api/v1"
    v1 := r.Group("/api/v1")
    {
        eg := v1.Group("/example")
        {
            eg.GET("/helloworld",Helloworld)
        }
    }
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
    r.Run(":8080")
}

注释格式请参考:通用API信息

gin-swagger项目官网:gin-swagger