0
点赞
收藏
分享

微信扫一扫

gin集成Swagger-UI

mafa1993 2022-03-30 阅读 83

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

1. 安装Swagger

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

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

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

swag init

生成目录如下:

使用以下命令下载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.
举报

相关推荐

0 条评论