swagger

package
v0.0.0-...-fb81f76 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 23, 2026 License: MIT Imports: 11 Imported by: 0

README

Swagger 组件

基于 swaggo/swag 实现的 Swagger/OpenAPI 文档支持。

功能特性

  • 🔧 注释驱动:在 Handler 上添加注释即可生成文档
  • 🚀 自动集成:启用后 HTTP Application 自动挂载 Swagger UI 和 Spec 路由
  • ⚙️ 配置化:通过 YAML 配置启用/禁用和自定义路径
  • 🔌 DI 集成:通过 samber/do 自动注入

快速开始

1. 配置启用

在应用配置文件中添加:

swagger:
  enabled: true
  ui_path: "/swagger/*any"      # Swagger UI 路径
  spec_path: "/openapi.json"    # OpenAPI Spec 路径
  info:
    title: "My API"
    description: "API 接口文档"
    version: "1.0.0"
    base_path: "/api"
2. 添加注释

在 Handler 上添加 Swagger 注释:

// GetUser 获取用户信息
//
//	@Summary		获取用户信息
//	@Description	根据 ID 获取用户详细信息
//	@Tags			用户
//	@Accept			json
//	@Produce		json
//	@Param			id	path		int					true	"用户 ID"
//	@Success		200	{object}	httpx.Response{data=User}	"成功"
//	@Failure		404	{object}	httpx.Response			"用户不存在"
//	@Router			/users/{id} [get]
func (h *Handler) GetUser(c *gin.Context) {
    // ...
}
3. main.go 添加注释

main.go 添加全局 API 信息:

package main

import (
    _ "your-app/docs" // 导入 swag 生成的 docs 包
)

// @title Your API
// @version 1.0.0
// @description API 接口文档

// @host localhost:8080
// @BasePath /api

// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
// @description JWT Bearer Token

func main() {
    // ...
}
4. 生成文档
# 安装 swag CLI
go install github.com/swaggo/swag/cmd/swag@latest

# 生成文档
swag init --parseDependency --parseInternal -g main.go -o docs
5. 启动应用

启动应用后访问:

  • Swagger UI: http://localhost:8080/swagger/index.html
  • OpenAPI Spec: http://localhost:8080/openapi.json

配置项

配置项 类型 默认值 说明
enabled bool false 是否启用 Swagger
ui_path string /swagger/*any Swagger UI 路由路径
spec_path string /openapi.json OpenAPI Spec 路由路径
deep_linking bool true 是否启用深度链接
persist_authorization bool true 是否持久化认证信息
info.title string API Documentation API 标题
info.description string - API 描述
info.version string 1.0.0 API 版本
info.base_path string /api API 基础路径

API

Manager
// 创建 Manager
mgr := swagger.NewManager(cfg, info, logger)

// 注册路由
mgr.RegisterRoutes(engine)

// 检查是否启用
if mgr.IsEnabled() {
    // ...
}
Helper 函数
// 快捷设置(从 DI 获取 Manager 并注册路由)
swagger.Setup(injector, engine)

// 带 Info 设置(用于动态配置)
swagger.SetupWithInfo(injector, engine)

// Must 版本(失败时 panic)
swagger.MustSetup(injector, engine)

注意事项

  1. 导入 docs 包:main.go 必须导入 swag 生成的 docs 包
  2. 注释格式:遵循 swag 标准注释格式
  3. 重新生成:修改注释后需重新运行 swag init
  4. 生产环境:建议在生产环境禁用 Swagger

常见问题

Q: 启动时提示 "swag.SwaggerInfo not initialized"

A: 确保 main.go 中导入了 _ "your-app/docs" 包。

Q: 文档未更新

A: 重新运行 swag init 命令生成文档。

Q: 如何支持多语言

A: 目前 swaggo 原生不支持多语言,可以通过配置不同的 docs 包实现。

Documentation

Overview

The package swagger provides capabilities for generating and displaying Swagger/OpenAPI documentation Based on swaggo/swag for documentation generation driven by comments

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSwaggerDisabled Swagger is not enabled
	ErrSwaggerDisabled = errcode.Register(errcode.New(
		moduleCodeSwagger, 1, "swagger", "swagger.disabled", "Swagger is disabled", http.StatusServiceUnavailable,
	))

	// ErrSwaggerInitFailed Swagger initialization failed
	ErrSwaggerInitFailed = errcode.Register(errcode.New(
		moduleCodeSwagger, 2, "swagger", "swagger.init_failed", "Swagger initialization failed", http.StatusInternalServerError,
	))

	// ErrSwaggerDocNotFound Swagger document not found
	ErrSwaggerDocNotFound = errcode.Register(errcode.New(
		moduleCodeSwagger, 3, "swagger", "swagger.doc_not_found", "Swagger documentation not found", http.StatusNotFound,
	))
)

Error code definitions

View Source
var BuildTime = time.Now().Format(time.RFC3339)

BuildTime records the generation time of swag (for debugging)

Functions

func MustSetup

func MustSetup(injector do.Injector, engine *gin.Engine)

MustSetup shortcut method: Set up Swagger (panic on failure)

func Setup

func Setup(injector do.Injector, engine *gin.Engine) error

Setup quick method: Obtain Manager from DI container and register routes The application layer can call this method in the OnReady callback

Using examples:

import _ "your-app/docs" // import the docs package generated by swag init

func (a *App) onReady(core *application.Application) error {
    swagger.Setup(core.GetInjector(), core.GetHTTPServer().GetEngine())
    return nil
}

func SetupWithInfo

func SetupWithInfo(injector do.Injector, engine *gin.Engine) error

SetupWithInfo shortcut method: Set up SwaggerInfo and register routes For scenarios requiring dynamic setting of API information

Usage example:

import (
    _ "your-app/docs"
    "your-app/docs"
)

func (a *App) onReady(core *application.Application) error {

// Dynamically set API information

    docs.SwaggerInfo.Title = a.GetConfig().App.Name + " API"
    docs.SwaggerInfo.Version = a.GetVersion()
    docs.SwaggerInfo.Host = a.GetConfig().ApiServer.Host
    docs.SwaggerInfo.BasePath = "/api/v1"

    swagger.SetupWithInfo(core.GetInjector(), core.GetHTTPServer().GetEngine())
    return nil
}

Types

type Config

type Config struct {
	// Enabled whether to enable Swagger (default false)
	Enabled bool `mapstructure:"enabled"`

	// UIPath Swagger UI route path (default "/swagger/*any")
	UIPath string `mapstructure:"ui_path"`

	// SpecPath OpenAPI Spec route path (default "/openapi.json")
	SpecPath string `mapstructure:"spec_path"`

	// DocJSONPath path for the doc.json generated by Swag (defaults to embedded)
	// If empty, use swag generated docs.SwaggerInfo
	DocJSONPath string `mapstructure:"doc_json_path"`

	// Whether deep linking is enabled (default true)
	DeepLinking bool `mapstructure:"deep_linking"`

	// Whether to persist authorization information (default true)
	PersistAuthorization bool `mapstructure:"persist_authorization"`

	// ValidatorURL validator URL (empty string disables validation)
	ValidatorURL string `mapstructure:"validator_url"`

	// OAuth2RedirectURL OAuth 2.0 redirect URL
	OAuth2RedirectURL string `mapstructure:"oauth2_redirect_url"`
}

Configure Swagger settings

func DefaultConfig

func DefaultConfig() Config

Returns default configuration

func (*Config) ApplyDefaults

func (c *Config) ApplyDefaults()

Apply defaults

func (*Config) Validate

func (c *Config) Validate() error

Validate configuration

type ContactInfo

type ContactInfo struct {
	Name  string `mapstructure:"name"`
	URL   string `mapstructure:"url"`
	Email string `mapstructure:"email"`
}

ContactInfo Contact information

type LicenseInfo

type LicenseInfo struct {
	Name string `mapstructure:"name"`
	URL  string `mapstructure:"url"`
}

LicenseInfo license information

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager Swagger Manager Encapsulate swaggo initialization and Gin middleware mounting

func NewManager

func NewManager(cfg Config, info SwaggerInfo, log *logger.CtxZapLogger) *Manager

Create Swagger Manager

func ProvideManager

func ProvideManager(i do.Injector) (*Manager, error)

ProvideManager creates the Swagger Manager's samber/do provider

func (*Manager) GetConfig

func (m *Manager) GetConfig() Config

GetConfig returns configuration

func (*Manager) GetInfo

func (m *Manager) GetInfo() SwaggerInfo

GetInfo returns API documentation metadata

func (*Manager) IsEnabled

func (m *Manager) IsEnabled() bool

Returns whether Swagger is enabled

func (*Manager) RegisterRoutes

func (m *Manager) RegisterRoutes(engine *gin.Engine)

RegisterRoutes registers Swagger routes to the Gin Engine This method is called by the application layer to mount Swagger UI and Spec routes

Usage example:

import _ "your-app/docs" // import the docs package generated by swag init

swaggerManager.RegisterRoutes(engine)

func (*Manager) SetupInfo

func (m *Manager) SetupInfo()

SetupInfo sets up swag.SwaggerInfo (call before route registration) This method synchronizes the configured metadata to the swag global variable

func (*Manager) Shutdown

func (m *Manager) Shutdown() error

Shutdown shutdown manager (implements do.Shutdownable)

type SecurityDefinition

type SecurityDefinition struct {
	Type             string            `mapstructure:"type"` // "apiKey", "oauth2", "basic"
	Description      string            `mapstructure:"description"`
	Name             string            `mapstructure:"name"` // Header/Query Parameter Names
	In               string            `mapstructure:"in"`   // "header", "query"
	Flow             string            `mapstructure:"flow"` // OAuth2 flow
	AuthorizationURL string            `mapstructure:"authorization_url"`
	TokenURL         string            `mapstructure:"token_url"`
	Scopes           map[string]string `mapstructure:"scopes"`
}

SecurityDefinition Security definition

type SwaggerInfo

type SwaggerInfo struct {
	// Title API title (corresponds to @title)
	Title string `mapstructure:"title"`

	// Description API description (corresponding to @description)
	Description string `mapstructure:"description"`

	// Version API version (corresponds to @version)
	Version string `mapstructure:"version"`

	// Host host address (corresponds to @host)
	// Leave blank for automatic detection
	Host string `mapstructure:"host"`

	// BasePath API base path (corresponds to @BasePath)
	BasePath string `mapstructure:"base_path"`

	// Schemes supported protocols (corresponding to @schemes)
	// For example: ["http", "https"]
	Schemes []string `mapstructure:"schemes"`

	// Contact information
	Contact *ContactInfo `mapstructure:"contact"`

	// License information
	License *LicenseInfo `mapstructure:"license"`

	// Security Definitions
	SecurityDefinitions map[string]*SecurityDefinition `mapstructure:"security_definitions"`
}

SwaggerInfo API metadata Corresponds to swag's @title, @version annotations etc.

func DefaultSwaggerInfo

func DefaultSwaggerInfo() SwaggerInfo

DefaultSwaggerInfo returns the default API documentation metadata

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL