Swagger
用于 Fiber 的 Swagger 中间件。该中间件处理 Swagger UI。
注意:需要 Go 1.18 或更高版本
目录
签名
func New(config ...swagger.Config) fiber.Handler
安装
Swagger 在支持模块的最新 Go 版本上进行了测试。因此,如果你还没有初始化模块,请确保先初始化。
go mod init github.com/<user>/<repo>
然后安装 swagger 中间件
go get github.com/gofiber/contrib/swagger
示例
导入中间件包
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/contrib/swagger"
)
使用默认配置
app.Use(swagger.New())
使用自定义配置
cfg := swagger.Config{
BasePath: "/",
FilePath: "./docs/swagger.json",
Path: "swagger",
Title: "Swagger API Docs",
}
app.Use(swagger.New(cfg))
使用程序数据作为 Swagger 内容
cfg := swagger.Config{
BasePath: "/",
FilePath: "./docs/swagger.json",
FileContent: mySwaggerByteSlice,
Path: "swagger",
Title: "Swagger API Docs",
}
app.Use(swagger.New(cfg))
使用多个 Swagger 实例
// Create Swagger middleware for v1
//
// Swagger will be available at: /api/v1/docs
app.Use(swagger.New(swagger.Config{
BasePath: "/api/v1/",
FilePath: "./docs/v1/swagger.json",
Path: "docs",
}))
// Create Swagger middleware for v2
//
// Swagger will be available at: /api/v2/docs
app.Use(swagger.New(swagger.Config{
BasePath: "/api/v2/",
FilePath: "./docs/v2/swagger.json",
Path: "docs",
}))
配置
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// BasePath for the UI path
//
// Optional. Default: /
BasePath string
// FilePath for the swagger.json or swagger.yaml file
//
// Optional. Default: ./swagger.json
FilePath string
// FileContent for the content of the swagger.json or swagger.yaml file.
// If provided, FilePath will not be read.
//
// Optional. Default: nil
FileContent []byte
// Path combines with BasePath for the full UI path
//
// Optional. Default: docs
Path string
// Title for the documentation site
//
// Optional. Default: Fiber API documentation
Title string
// CacheAge defines the max-age for the Cache-Control header in seconds.
//
// Optional. Default: 3600 (1 hour)
CacheAge int
}
默认配置
var ConfigDefault = Config{
Next: nil,
BasePath: "/",
FilePath: "./swagger.json",
Path: "docs",
Title: "Fiber API documentation",
CacheAge: 3600, // Default to 1 hour
}