Go Gin框架集成Swagger
package main
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
)
// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/
// @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
// @host petstore.swagger.io
// @BasePath /v2
// @schemes http https
// @securityDefinitions.basic BasicAuth
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name X-API-KEY
// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.admin Grants admin access
// @scope.user Grants user access
// @securitydefinitions.oauth2.implicit OAuth2Implicit
// @authorizationUrl https://example.com/oauth/authorize
// @scope.write Grants write access
// @scope.read Grants read access
// @securitydefinitions.oauth2.password OAuth2Password
// @tokenUrl https://example.com/oauth/token
// @scope.admin Grants admin access
// @scope.user Grants user access
// @securitydefinitions.oauth2.accessCode OAuth2AccessCode
// @tokenUrl https://example.com/oauth/token
// @authorizationUrl https://example.com/oauth/authorize
// @scope.admin Grants admin access
// @scope.user Grants user access
func main() {
r := gin.Default()
// 当前Swagger文档的接口
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
// 你的API路由...
r.Run() // 启动服务在localhost:8080
}
这个代码实例展示了如何在Go Gin框架中集成Swagger。首先,我们导入了必要的Swagger相关的包。然后,我们定义了一些Swagger的注解,这些注解描述了API的标题、版本、描述等信息。在main
函数中,我们使用ginSwagger.WrapHandler(swaggerFiles.Handler)
为Swagger提供了一个接口,这样就可以通过/swagger/*any
路径访问Swagger UI。最后,我们启动Gin服务器。这个例子简洁明了,展示了如何将Swagger集成到Gin项目中。
评论已关闭