swagger

package module
v1.6.3 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

README

Swagger Plugin for Lynx

lynx-swagger generates Swagger/OpenAPI documents and serves a separate Swagger UI HTTP endpoint.

Environment boundary: the current module is recommended only for development and testing environments. The runtime guard path still blocks production and staging by default, and the shipped configuration examples are intentionally aligned to dev/test use only.

Runtime facts

  • Go module: github.com/go-lynx/lynx-swagger
  • Config prefix: lynx.swagger
  • Runtime plugin name: swagger
  • Getter boundary: use the plugin instance and (*PlugSwagger).GetSwagger() if you need the in-memory spec

Current runtime surface

The current runtime reads these YAML sections:

  • lynx.swagger.enabled
  • lynx.swagger.generator
  • lynx.swagger.ui
  • lynx.swagger.info
  • lynx.swagger.security
  • lynx.swagger.api_server

The shipped templates in conf now reflect the live keys the runtime actually consumes.

Minimal working configuration

lynx:
  swagger:
    enabled: true
    generator:
      enabled: true
      scan_dirs:
        - "./app"
      output_path: "./docs/openapi.yaml"
      watch_files: true
      file_watcher:
        enabled: true
        interval: 1s
        debounce_delay: 500ms
        max_retries: 3
        retry_delay: 1s
        batch_size: 10
        health_check: true
    ui:
      enabled: true
      port: 8081
      path: "/swagger"
      deepLinking: true
      docExpansion: "list"
    info:
      title: "My API"
      version: "1.0.0"
      description: "Runtime API documentation"
    api_server:
      host: "localhost:8080"
      base_path: "/api/v1"

Important behavior notes

  • generator.watch_files is the real watcher switch.
  • generator.file_watcher.* now controls watcher timing and retry behavior.
  • info.title is the title used both in the generated spec and in the current HTML page.
  • api_server.host controls where Swagger UI sends "Try it out" requests. If it is empty, the plugin tries to derive it from lynx.http.addr.
  • The current HTML uses ui.deepLinking and ui.docExpansion.
  • ui.displayRequestDuration, ui.defaultModelsExpandDepth, and security.require_auth are parsed but not enforced/rendered by the current handler.

Parsed but not effective today

The following fields are parsed from configuration but are not fully effective in the current runtime:

  • security.require_auth: stored in config, but the current HTTP handler does not enforce extra UI authentication
  • ui.displayRequestDuration: parsed, but the current HTML template does not render the request-duration toggle
  • ui.defaultModelsExpandDepth: parsed, but the current HTML template does not apply the model expansion depth option

Keys you should not rely on

Do not use template-era keys that are not wired into the current runtime, including:

  • generator.watch_enabled
  • generator.watch_interval
  • generator.gen_on_startup
  • ui.title
  • ui.spec_url
  • ui.auto_refresh
  • ui.refresh_interval
  • snake_case UI keys such as ui.deep_linking or ui.doc_expansion
  • top-level Swagger metadata blocks such as servers, schemes, consumes, produces, security_definitions, and advanced

Environment and production boundary

  • By default the plugin is allowed only in development and testing.
  • Production and staging remain blocked by the current runtime guard path.
  • disable_in_production is effectively treated as true by the current defaulting logic, so do not plan on enabling Swagger in production without changing code.

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

View Source
const (
	EnvDevelopment = "development"
	EnvTesting     = "testing"
	EnvStaging     = "staging"
	EnvProduction  = "production"
)

Environment types

Variables

This section is empty.

Functions

func GenerateSwaggerUIHTML

func GenerateSwaggerUIHTML(specURL, title string) string

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 Field

type Field struct {
	Name     string
	Type     string
	Tag      string
	Required bool
	Doc      string
}

Field represents a single struct field with its JSON/YAML tag and doc comment.

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

type HeaderInfo struct {
	Type        string
	Format      string
	Description string
}

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 Package

type Package struct {
	Name    string
	Structs map[string]*Struct
}

Package holds the parsed structs from a single Go package.

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

type ParseError struct {
	File    string
	Line    int
	Message string
	Type    string
	Time    time.Time
}

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) Health

func (p *PlugSwagger) Health() error

Health health check

func (*PlugSwagger) InitializeContext added in v1.6.1

func (p *PlugSwagger) InitializeContext(ctx context.Context, plugin plugins.Plugin, rt plugins.Runtime) error

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 (p *PlugSwagger) StartContext(ctx context.Context, _ plugins.Plugin) error

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 (p *PlugSwagger) StopContext(ctx context.Context, _ plugins.Plugin) error

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 Response

type Response struct {
	Description string
	Schema      any
	Examples    map[string]any
}

Response describes a possible HTTP response for a route.

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 Struct

type Struct struct {
	Name   string
	Fields []Field
	Doc    string
}

Struct holds the parsed fields and doc comment for a named struct.

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.

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.

Jump to

Keyboard shortcuts

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