当前位置: 首页 > 工具软件 > Swagger-more > 使用案例 >

gin集成Swagger-UI

郎伟兆
2023-12-01

gin 中间件使用 Swagger 2.0 自动生成 RESTFUL API 文档。

完整例子:

https://github.com/Mzihao/go-logistics

1. 安装Swagger

使用以下命令下载Swag for Go:

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

在 Go 项目根路径运行Swag , Swag将解析注释并生成所需的文件和文件夹。

swag init

# 可加载外部包
swag init --parseDependency --

参数解释:

参数名含义解释
parseInternal解析内部依赖包,默认值: false
parseDependency解析外部依赖包,默认值: false
parseDepth解析依赖包深度,默认值:100

生成目录如下:

.
├── docs
│ ├── docs.go
│ ├── swagger.json
│ └── swagger.yaml
├── go.mod
├── go.sum
└── main.go

使用以下命令下载gin-swagger:

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

一个完整的例子:

package main

import (
   "github.com/gin-gonic/gin"
   docs "github.com/go-project-name/docs"
   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.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")

}

在http://localhost:8080/swagger/index.html 中查看

配置

您可以使用不同的配置选项来配置 Swagger

func main() {
	r := gin.New()

	ginSwagger.WrapHandler(swaggerFiles.Handler,
		ginSwagger.URL("http://localhost:8080/swagger/doc.json"),
		ginSwagger.DefaultModelsExpandDepth(-1))

	r.Run()
}
选项类型默认描述
URLstring“doc.json”URL pointing to API definition
DocExpansionstring“list”Controls the default expansion setting for the operations and tags. It can be ‘list’ (expands only the tags), ‘full’ (expands the tags and operations) or ‘none’ (expands nothing).
DeepLinkingbooltrueIf set to true, enables deep linking for tags and operations. See the Deep Linking documentation for more information.
DefaultModelsExpandDepthint1Default expansion depth for models (set to -1 completely hide the models).
InstanceNamestring“swagger”The instance name of the swagger document. If multiple different swagger instances should be deployed on one gin router, ensure that each instance has a unique name (use the --instanceName parameter to generate swagger documents with swag init).
PersistAuthotizationboolfalseIf set to true, it persists authorization data and it would not be lost on browser close/refresh.
 类似资料: