Documentation
¶
Overview ¶
Package swagger provides a Swagger/OpenAPI documentation plugin for the go-lynx framework. It loads external OpenAPI/Swagger spec files, optionally scans Go source annotations, merges them into a unified Swagger 2.0 document, and serves a built-in Swagger UI on a configurable HTTP port. Route registration and spec access are protected by a sync.RWMutex so the plugin is safe for concurrent use.
Index ¶
- Constants
- func GenerateSwaggerUIHTML(specURL, title string) string
- type AnnotationParser
- func (p *AnnotationParser) BuildSwagger() error
- func (p *AnnotationParser) ClearCache()
- func (p *AnnotationParser) GetErrorSummary() map[string]int
- func (p *AnnotationParser) GetMemoryStats() map[string]any
- func (p *AnnotationParser) GetStats() *ParseStats
- func (p *AnnotationParser) OptimizeMemory()
- func (p *AnnotationParser) ParseFile(filename string) error
- func (p *AnnotationParser) ParseParam(line string) *ParamInfo
- func (p *AnnotationParser) ParseResponse(line string) (int, *ResponseInfo)
- func (p *AnnotationParser) ScanDirectory(dir string) error
- type ApiServerConfig
- type Field
- type FileWatcher
- type FileWatcherConfig
- type GenConfig
- type Generator
- type HeaderInfo
- type InfoConfig
- type ModelInfo
- type Package
- type ParamInfo
- type Parameter
- type ParseError
- type ParseStats
- type Parser
- type PlugSwagger
- func (p *PlugSwagger) AddDefinition(name string, schema spec.Schema)
- func (p *PlugSwagger) AddPath(path string, item spec.PathItem)
- func (p *PlugSwagger) CheckHealth() error
- func (p *PlugSwagger) CleanupTasks() error
- func (p *PlugSwagger) GetSwagger() *spec.Swagger
- func (p *PlugSwagger) Health() error
- func (p *PlugSwagger) InitializeContext(ctx context.Context, plugin plugins.Plugin, rt plugins.Runtime) error
- func (p *PlugSwagger) InitializeResources(rt plugins.Runtime) error
- func (p *PlugSwagger) IsContextAware() bool
- func (p *PlugSwagger) PluginProtocol() plugins.PluginProtocol
- func (p *PlugSwagger) SetDefaultValues()
- func (p *PlugSwagger) StartContext(ctx context.Context, _ plugins.Plugin) error
- func (p *PlugSwagger) StartupTasks() error
- func (p *PlugSwagger) StopContext(ctx context.Context, _ plugins.Plugin) error
- func (p *PlugSwagger) UpdateSwagger(swagger *spec.Swagger)
- type PropertyInfo
- type Response
- type ResponseInfo
- type Route
- type RouteInfo
- type SchemaInfo
- type SecurityConfig
- type StringBuilderPool
- type Struct
- type SwaggerConfig
- type UIConfig
Constants ¶
const ( EnvDevelopment = "development" EnvTesting = "testing" EnvStaging = "staging" EnvProduction = "production" )
Environment types
Variables ¶
This section is empty.
Functions ¶
func GenerateSwaggerUIHTML ¶
GenerateSwaggerUIHTML generates Swagger UI HTML (kept for backward compatibility) Deprecated: Use ui.Handler instead
Types ¶
type AnnotationParser ¶
type AnnotationParser struct {
// contains filtered or unexported fields
}
AnnotationParser annotation parser with memory management
func NewAnnotationParser ¶
func NewAnnotationParser(swagger *spec.Swagger, allowedDirs []string) *AnnotationParser
NewAnnotationParser creates an annotation parser
func (*AnnotationParser) BuildSwagger ¶
func (p *AnnotationParser) BuildSwagger() error
BuildSwagger builds Swagger specification
func (*AnnotationParser) ClearCache ¶
func (p *AnnotationParser) ClearCache()
ClearCache clears all caches and resets statistics
func (*AnnotationParser) GetErrorSummary ¶
func (p *AnnotationParser) GetErrorSummary() map[string]int
GetErrorSummary returns a summary of parsing errors
func (*AnnotationParser) GetMemoryStats ¶
func (p *AnnotationParser) GetMemoryStats() map[string]any
GetMemoryStats returns memory usage statistics.
func (*AnnotationParser) GetStats ¶
func (p *AnnotationParser) GetStats() *ParseStats
GetStats returns parsing statistics
func (*AnnotationParser) OptimizeMemory ¶
func (p *AnnotationParser) OptimizeMemory()
OptimizeMemory optimizes memory usage
func (*AnnotationParser) ParseFile ¶
func (p *AnnotationParser) ParseFile(filename string) error
ParseFile parses a file with comprehensive error handling
func (*AnnotationParser) ParseParam ¶
func (p *AnnotationParser) ParseParam(line string) *ParamInfo
ParseParam parses parameter annotations (public method for testing) Format: @Param name in type format required "description" default(value) example(value)
func (*AnnotationParser) ParseResponse ¶
func (p *AnnotationParser) ParseResponse(line string) (int, *ResponseInfo)
ParseResponse parses response annotations (public method for testing) Format: @Success 200 {object} model.Response "description"
func (*AnnotationParser) ScanDirectory ¶
func (p *AnnotationParser) ScanDirectory(dir string) error
ScanDirectory scans directory
type ApiServerConfig ¶ added in v1.5.5
type ApiServerConfig struct {
Host string `json:"host" yaml:"host"` // e.g. "localhost:8080" (lynx-http listen address)
BasePath string `json:"base_path" yaml:"base_path"` // e.g. "/api/v1"
}
ApiServerConfig configures the API server URL used by Swagger UI "Try it out". If empty, reads from lynx.http.addr.
type FileWatcher ¶
type FileWatcher struct {
// contains filtered or unexported fields
}
FileWatcher polls the configured spec files and calls callback when changes are detected.
func (*FileWatcher) GetStats ¶
func (w *FileWatcher) GetStats() map[string]any
GetStats returns file watcher statistics.
func (*FileWatcher) IsHealthy ¶
func (w *FileWatcher) IsHealthy() bool
IsHealthy returns the health status of the file watcher
type FileWatcherConfig ¶
type FileWatcherConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Interval time.Duration `json:"interval" yaml:"interval"`
DebounceDelay time.Duration `json:"debounce_delay" yaml:"debounce_delay"`
MaxRetries int `json:"max_retries" yaml:"max_retries"`
RetryDelay time.Duration `json:"retry_delay" yaml:"retry_delay"`
BatchSize int `json:"batch_size" yaml:"batch_size"`
HealthCheck bool `json:"health_check" yaml:"health_check"`
}
FileWatcherConfig controls the polling interval, debounce window, and retry behaviour.
type GenConfig ¶
type GenConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
ScanDirs []string `json:"scan_dirs" yaml:"scan_dirs"`
SpecFiles []string `json:"spec_files" yaml:"spec_files"` // External OpenAPI/Swagger files (YAML or JSON, OAS2 or OAS3)
OutputPath string `json:"output_path" yaml:"output_path"`
WatchFiles bool `json:"watch_files" yaml:"watch_files"`
FileWatcher FileWatcherConfig `json:"file_watcher" yaml:"file_watcher"`
}
GenConfig controls spec generation: source scan directories, external spec files, and file watching.
type Generator ¶
type Generator struct {
// contains filtered or unexported fields
}
Generator builds the unified Swagger spec from source annotations and external spec files.
type HeaderInfo ¶
HeaderInfo response header information
type InfoConfig ¶
type InfoConfig struct {
Title string `json:"title" yaml:"title"`
Description string `json:"description" yaml:"description"`
Version string `json:"version" yaml:"version"`
TermsOfService string `json:"termsOfService" yaml:"termsOfService"`
Contact struct {
Name string `json:"name" yaml:"name"`
Email string `json:"email" yaml:"email"`
URL string `json:"url" yaml:"url"`
} `json:"contact" yaml:"contact"`
License struct {
Name string `json:"name" yaml:"name"`
URL string `json:"url" yaml:"url"`
} `json:"license" yaml:"license"`
}
InfoConfig holds the top-level metadata fields exposed in the Swagger spec.
type ModelInfo ¶
type ModelInfo struct {
Name string
Description string
Properties map[string]PropertyInfo
Required []string
}
ModelInfo model information
type ParamInfo ¶
type ParamInfo struct {
Name string
In string // path, query, header, body, formData
Type string
Format string
Required bool
Description string
Default any
Example any
}
ParamInfo parameter information
type Parameter ¶
type Parameter struct {
Name string
In string
Type string
Required bool
Description string
Example string
}
Parameter describes a single route input (path, query, body, etc.).
type ParseError ¶
ParseError detailed error information
type ParseStats ¶
type ParseStats struct {
TotalFiles int
SuccessFiles int
FailedFiles int
TotalLines int
ParsedRoutes int
ParsedModels int
Errors []ParseError
StartTime time.Time
EndTime time.Time
}
ParseStats statistics for parsing operations
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser scans Go source packages for route and struct annotations.
type PlugSwagger ¶
type PlugSwagger struct {
*plugins.BasePlugin
// contains filtered or unexported fields
}
PlugSwagger is the Swagger UI and spec-serving plugin.
func NewSwaggerPlugin ¶
func NewSwaggerPlugin() *PlugSwagger
NewSwaggerPlugin creates a Swagger plugin instance with sensible defaults.
func (*PlugSwagger) AddDefinition ¶
func (p *PlugSwagger) AddDefinition(name string, schema spec.Schema)
AddDefinition adds definition
func (*PlugSwagger) AddPath ¶
func (p *PlugSwagger) AddPath(path string, item spec.PathItem)
AddPath adds path
func (*PlugSwagger) CheckHealth ¶
func (p *PlugSwagger) CheckHealth() error
CheckHealth health check
func (*PlugSwagger) CleanupTasks ¶
func (p *PlugSwagger) CleanupTasks() error
CleanupTasks stops the file watcher and shuts down the UI HTTP server.
func (*PlugSwagger) GetSwagger ¶
func (p *PlugSwagger) GetSwagger() *spec.Swagger
GetSwagger gets Swagger specification
func (*PlugSwagger) InitializeContext ¶ added in v1.6.1
func (*PlugSwagger) InitializeResources ¶
func (p *PlugSwagger) InitializeResources(rt plugins.Runtime) error
InitializeResources loads the Swagger config from the runtime config tree.
func (*PlugSwagger) IsContextAware ¶ added in v1.6.1
func (p *PlugSwagger) IsContextAware() bool
func (*PlugSwagger) PluginProtocol ¶ added in v1.6.1
func (p *PlugSwagger) PluginProtocol() plugins.PluginProtocol
func (*PlugSwagger) SetDefaultValues ¶
func (p *PlugSwagger) SetDefaultValues()
SetDefaultValues sets default values for configuration
func (*PlugSwagger) StartContext ¶ added in v1.6.1
func (*PlugSwagger) StartupTasks ¶
func (p *PlugSwagger) StartupTasks() error
StartupTasks generates the Swagger spec and starts the UI server.
func (*PlugSwagger) StopContext ¶ added in v1.6.1
func (*PlugSwagger) UpdateSwagger ¶
func (p *PlugSwagger) UpdateSwagger(swagger *spec.Swagger)
UpdateSwagger updates Swagger specification
type PropertyInfo ¶
type PropertyInfo struct {
Type string
Format string
Description string
Example any
Enum []any
Minimum *float64
Maximum *float64
MinLength *int64
MaxLength *int64
Pattern string
}
PropertyInfo property information
type ResponseInfo ¶
type ResponseInfo struct {
Description string
Schema *SchemaInfo
Headers map[string]HeaderInfo
}
ResponseInfo response information
type Route ¶
type Route struct {
Method string
Path string
Handler string
Summary string
Description string
Tags []string
Parameters []Parameter
Responses map[string]Response
}
Route holds the metadata for a single parsed HTTP endpoint.
type RouteInfo ¶
type RouteInfo struct {
Method string
Path string
Summary string
Description string
Tags []string
Params []ParamInfo
Responses map[int]ResponseInfo
Security []map[string][]string
}
RouteInfo route information
type SchemaInfo ¶
type SchemaInfo struct {
Type string
Format string
Ref string
Properties map[string]*SchemaInfo
Items *SchemaInfo
Required []string
}
SchemaInfo schema information
type SecurityConfig ¶
type SecurityConfig struct {
Environment string `json:"environment" yaml:"environment"`
AllowedEnvs []string `json:"allowed_environments" yaml:"allowed_environments"`
DisableInProd bool `json:"disable_in_production" yaml:"disable_in_production"`
TrustedOrigins []string `json:"trusted_origins" yaml:"trusted_origins"`
RequireAuth bool `json:"require_auth" yaml:"require_auth"`
// AuthToken, when set, is the expected bearer token presented via the
// "Authorization: Bearer <token>" header when RequireAuth is true.
AuthToken string `json:"auth_token" yaml:"auth_token"`
// AuthUsername/AuthPassword, when set, enable HTTP Basic auth as an
// alternative to AuthToken when RequireAuth is true.
AuthUsername string `json:"auth_username" yaml:"auth_username"`
AuthPassword string `json:"auth_password" yaml:"auth_password"`
}
SecurityConfig restricts which environments and callers may access the UI.
type StringBuilderPool ¶
type StringBuilderPool struct {
// contains filtered or unexported fields
}
StringBuilderPool string builder object pool
func NewStringBuilderPool ¶
func NewStringBuilderPool(size int) *StringBuilderPool
NewStringBuilderPool creates a new string builder pool
func (*StringBuilderPool) Get ¶
func (p *StringBuilderPool) Get() *strings.Builder
Get gets a string builder from pool
func (*StringBuilderPool) Put ¶
func (p *StringBuilderPool) Put(sb *strings.Builder)
Put returns a string builder to pool
type SwaggerConfig ¶
type SwaggerConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Info InfoConfig `json:"info" yaml:"info"`
UI UIConfig `json:"ui" yaml:"ui"`
Gen GenConfig `json:"generator" yaml:"generator"`
Security SecurityConfig `json:"security" yaml:"security"`
ApiServer ApiServerConfig `json:"api_server" yaml:"api_server"` // API server for Swagger UI "Try it out" (lynx-http address)
}
SwaggerConfig is the top-level configuration for the Swagger plugin.
type UIConfig ¶
type UIConfig struct {
Path string `json:"path" yaml:"path"`
Enabled bool `json:"enabled" yaml:"enabled"`
DeepLinking bool `json:"deepLinking" yaml:"deepLinking"`
DisplayRequestDuration bool `json:"displayRequestDuration" yaml:"displayRequestDuration"`
DocExpansion string `json:"docExpansion" yaml:"docExpansion"`
DefaultModelsExpandDepth int `json:"defaultModelsExpandDepth" yaml:"defaultModelsExpandDepth"`
Port int `json:"port" yaml:"port"`
// BindAddress is the network interface the UI server listens on. When
// empty it defaults to 127.0.0.1 (loopback only). Set explicitly to
// "0.0.0.0" (or a specific external interface) to expose the UI beyond
// the local host. ExposeExternally must also be true for any non-loopback bind.
BindAddress string `json:"bind_address" yaml:"bind_address"`
// ExposeExternally must be explicitly set to true to allow binding to a
// non-loopback address. This is an opt-in guard against accidentally
// serving the API spec/UI on all interfaces.
ExposeExternally bool `json:"expose_externally" yaml:"expose_externally"`
}
UIConfig controls the embedded Swagger UI server.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ui embeds the Swagger UI HTML template and exposes an HTTP handler that renders the Swagger UI page for a given API specification URL.
|
Package ui embeds the Swagger UI HTML template and exposes an HTTP handler that renders the Swagger UI page for a given API specification URL. |