Documentation
¶
Overview ¶
Package openapi provides automatic OpenAPI 3.0 specification generation for Aegis.
This plugin generates interactive API documentation with:
- OpenAPI 3.0.3 specification (JSON)
- Scalar documentation UI (interactive browser interface)
- Automatic schema generation from Go structs
- Security scheme definitions (cookie, bearer)
- Route metadata collection and transformation
Documentation Features:
- Auto-generates schemas from Go types using reflection
- Parses validation tags for schema constraints
- Supports request/response body documentation
- Security requirements (protected vs public routes)
- Tag-based organization
Route Structure:
- GET /openapi.json - OpenAPI specification (JSON)
- GET /docs - Scalar documentation UI (if enabled)
Usage:
cfg := &openapi.Config{
Title: "My API",
Version: "1.0.0",
EnableScalarUI: true,
}
plugin := openapi.New(cfg)
aegis.RegisterPlugin(plugin)
Package openapi provides OpenAPI 3.0 specification types and generation.
Index ¶
- type Components
- type Config
- type Contact
- type Handler
- type Header
- type Info
- type License
- type MediaType
- type OAuthFlow
- type OAuthFlows
- type Operation
- type Parameter
- type PathItem
- type Plugin
- func (p *Plugin) Dependencies() []plugins.Dependency
- func (p *Plugin) Description() string
- func (p *Plugin) GetMigrations() []plugins.Migration
- func (p *Plugin) GetSchemas() []plugins.Schema
- func (p *Plugin) GetSpec() *Spec
- func (p *Plugin) Init(_ context.Context, _ plugins.Aegis) error
- func (p *Plugin) MountRoutes(router router.Router, prefix string)
- func (p *Plugin) Name() string
- func (p *Plugin) ProvidesAuthMethods() []string
- func (p *Plugin) RegisterEndpoint(method, path string, operation *Operation)
- func (p *Plugin) RegisterRouteMetadata(meta core.RouteMetadata)
- func (p *Plugin) RegisterSchema(name string, schema *Schema)
- func (p *Plugin) RegisterSchemaFromType(name string, example any)
- func (p *Plugin) RegisterSecurityScheme(name string, scheme *SecurityScheme)
- func (p *Plugin) RegisterTag(tag Tag)
- func (p *Plugin) RequiresTables() []string
- func (p *Plugin) UpdateSpec(metadata []core.RouteMetadata)
- func (p *Plugin) Version() string
- type RequestBody
- type Response
- type Schema
- func ArraySchema(description string, items *Schema) *Schema
- func BooleanSchema(description string) *Schema
- func DateTimeSchema(description string) *Schema
- func EmailSchema(description string) *Schema
- func GenerateSchema(v any) *Schema
- func IntegerSchema(description string) *Schema
- func ObjectSchema(description string, properties map[string]*Schema, required []string) *Schema
- func RefSchema(ref string) *Schema
- func StringSchema(description string) *Schema
- func UUIDSchema(description string) *Schema
- type SecurityRequirement
- type SecurityScheme
- type Server
- type ServerVariable
- type Spec
- type Tag
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Components ¶
type Components struct {
Schemas map[string]*Schema `json:"schemas,omitempty"`
Responses map[string]*Response `json:"responses,omitempty"`
Parameters map[string]*Parameter `json:"parameters,omitempty"`
RequestBodies map[string]*RequestBody `json:"requestBodies,omitempty"`
Headers map[string]*Header `json:"headers,omitempty"`
SecuritySchemes map[string]*SecurityScheme `json:"securitySchemes,omitempty"`
}
Components holds reusable objects for different aspects of the OAS.
type Config ¶
type Config struct {
// Title for the API documentation
Title string
// Version of the API
Version string
// Description of the API
Description string
// Servers to include in the spec (for multi-environment APIs)
Servers []Server
// Contact information for API maintainers
Contact *Contact
// License information for the API
License *License
// EnableScalarUI enables the Scalar documentation UI at /docs
EnableScalarUI bool
// BasePath for the API (e.g., "/auth", "/api/v1")
BasePath string
}
Config holds OpenAPI plugin configuration.
Example:
cfg := &openapi.Config{
Title: "Aegis Authentication API",
Version: "1.0.0",
Description: "Complete authentication API",
EnableScalarUI: true,
BasePath: "/auth",
Servers: []openapi.Server{
{URL: "https://api.example.com", Description: "Production"},
},
}
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns default OpenAPI configuration.
Default Settings:
- Title: "Aegis Authentication API"
- Version: "1.0.0"
- ScalarUI: Enabled
- BasePath: "/auth"
- Server: http://localhost:8080 (development)
- License: MIT
Returns:
- *Config: Default configuration ready for customization
type Contact ¶
type Contact struct {
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Email string `json:"email,omitempty"`
}
Contact information for the API.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles HTTP requests for OpenAPI documentation.
This handler serves:
- OpenAPI specification in JSON format
- Scalar interactive documentation UI
func NewHandler ¶
NewHandler creates a new OpenAPI handler.
Parameters:
- plugin: Initialized OpenAPI plugin
- router: Router instance for metadata collection
Returns:
- *Handler: Handler ready for route registration
func (*Handler) ServeScalarUI ¶
func (h *Handler) ServeScalarUI(w http.ResponseWriter, req *http.Request)
ServeScalarUI serves the Scalar documentation UI.
Scalar Features:
- Interactive API explorer
- Request/response examples
- Try-it-out functionality
- Authentication testing
- Schema visualization
Endpoint:
- Method: GET
- Path: /docs
- Auth: Public
Implementation: Uses CDN-hosted Scalar UI (https://cdn.jsdelivr.net/npm/@scalar/api-reference) Loads spec from ./openapi.json endpoint.
Example: Navigate to http://localhost:8080/auth/docs to view interactive documentation.
func (*Handler) ServeSpec ¶
func (h *Handler) ServeSpec(w http.ResponseWriter, _ *http.Request)
ServeSpec serves the OpenAPI specification as JSON.
This endpoint:
- Collects latest route metadata from router
- Updates OpenAPI spec with new routes
- Serializes spec to JSON
- Serves with CORS headers for documentation tools
Endpoint:
- Method: GET
- Path: /openapi.json
- Auth: Public
Response:
- Content-Type: application/json
- Access-Control-Allow-Origin: * (for Swagger UI, Postman, etc.)
Use Cases:
- Generate client SDKs
- Import into Postman/Insomnia
- Validate API contracts
- Feed documentation generators
type Header ¶
type Header struct {
Description string `json:"description,omitempty"`
Schema *Schema `json:"schema,omitempty"`
}
Header describes a single header parameter.
type Info ¶
type Info struct {
Title string `json:"title"`
Description string `json:"description,omitempty"`
TermsOfService string `json:"termsOfService,omitempty"`
Contact *Contact `json:"contact,omitempty"`
License *License `json:"license,omitempty"`
Version string `json:"version"`
}
Info provides metadata about the API.
Example:
info := Info{
Title: "Aegis API",
Version: "1.0.0",
Description: "Authentication API",
Contact: &Contact{
Name: "API Support",
Email: "[email protected]",
},
}
type MediaType ¶
type MediaType struct {
Schema *Schema `json:"schema,omitempty"`
Example any `json:"example,omitempty"`
}
MediaType provides schema and examples for the media type.
type OAuthFlow ¶
type OAuthFlow struct {
AuthorizationURL string `json:"authorizationUrl,omitempty"`
TokenURL string `json:"tokenUrl,omitempty"`
RefreshURL string `json:"refreshUrl,omitempty"`
Scopes map[string]string `json:"scopes"`
}
OAuthFlow configuration details.
type OAuthFlows ¶
type OAuthFlows struct {
Implicit *OAuthFlow `json:"implicit,omitempty"`
Password *OAuthFlow `json:"password,omitempty"`
ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty"`
AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty"`
}
OAuthFlows allows configuration of the supported OAuth Flows.
type Operation ¶
type Operation struct {
Tags []string `json:"tags,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
OperationID string `json:"operationId,omitempty"`
Parameters []Parameter `json:"parameters,omitempty"`
RequestBody *RequestBody `json:"requestBody,omitempty"`
Responses map[string]*Response `json:"responses"`
Security []SecurityRequirement `json:"security,omitempty"`
Deprecated bool `json:"deprecated,omitempty"`
}
Operation describes a single API operation on a path.
This represents an HTTP method (GET, POST, etc.) on a specific path. Each operation defines:
- Request requirements (parameters, body)
- Response definitions (status codes, schemas)
- Security requirements
- Metadata (tags, summary, description)
Example:
op := &Operation{
Tags: []string{"Default"},
Summary: "Login",
Description: "Authenticate user with email and password",
RequestBody: &RequestBody{...},
Responses: map[string]*Response{...},
Security: []SecurityRequirement{{"cookieAuth": []string{}}},
}
type Parameter ¶
type Parameter struct {
Name string `json:"name"`
In string `json:"in"` // "query", "header", "path", "cookie"
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
Schema *Schema `json:"schema,omitempty"`
Example any `json:"example,omitempty"`
}
Parameter describes a single operation parameter.
type PathItem ¶
type PathItem struct {
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Get *Operation `json:"get,omitempty"`
Post *Operation `json:"post,omitempty"`
Put *Operation `json:"put,omitempty"`
Delete *Operation `json:"delete,omitempty"`
Patch *Operation `json:"patch,omitempty"`
Options *Operation `json:"options,omitempty"`
Head *Operation `json:"head,omitempty"`
}
PathItem describes operations available on a single path.
type Plugin ¶
type Plugin struct {
// contains filtered or unexported fields
}
Plugin provides automatic OpenAPI 3.0 documentation generation.
This plugin integrates with the Aegis routing system to collect route metadata and generate comprehensive API documentation with interactive UI.
Features:
- Real-time spec generation from route metadata
- Thread-safe spec updates
- Scalar UI integration for interactive documentation
- Multiple security scheme support
- Schema validation from Go struct tags
func New ¶
New creates a new OpenAPI plugin with automatic schema generation.
Initialization:
- Create base OpenAPI 3.0.3 spec
- Configure servers, contact, license
- Add security schemes (cookie, bearer)
- Add default tags (default, Session)
- Add common schemas (Error, Success)
Parameters:
- cfg: Plugin configuration (uses defaults if nil)
Returns:
- *Plugin: Configured plugin ready for initialization
Example:
plugin := openapi.New(&openapi.Config{
Title: "My API",
Version: "2.0.0",
})
func (*Plugin) Dependencies ¶
func (p *Plugin) Dependencies() []plugins.Dependency
Dependencies returns plugin dependencies.
func (*Plugin) Description ¶
Description returns a human-readable description.
func (*Plugin) GetMigrations ¶
GetMigrations returns the plugin migrations.
func (*Plugin) GetSchemas ¶
GetSchemas returns all schemas for all supported dialects
func (*Plugin) MountRoutes ¶
MountRoutes registers HTTP routes for the plugin.
func (*Plugin) ProvidesAuthMethods ¶
ProvidesAuthMethods returns authentication methods provided.
func (*Plugin) RegisterEndpoint ¶
RegisterEndpoint adds a custom endpoint to the OpenAPI spec. This allows other plugins and user code to extend the documentation.
func (*Plugin) RegisterRouteMetadata ¶ added in v1.2.1
func (p *Plugin) RegisterRouteMetadata(meta core.RouteMetadata)
RegisterRouteMetadata adds a route to the OpenAPI spec from RouteMetadata. This provides a simpler interface for registering user-defined routes that aren't part of the Aegis authentication system.
Example:
openapiPlugin.RegisterRouteMetadata(core.RouteMetadata{
Method: "GET",
Path: "/api/subscriptions",
Summary: "List subscriptions",
Description: "Get all user subscriptions",
Tags: []string{"Subscriptions"},
Protected: true,
})
func (*Plugin) RegisterSchema ¶
RegisterSchema adds a reusable schema component.
func (*Plugin) RegisterSchemaFromType ¶
RegisterSchemaFromType automatically generates and registers an OpenAPI schema from a Go type. This eliminates the need for manual schema definitions and ensures schemas stay in sync with Go structs.
Example usage:
p.RegisterSchemaFromType("User", core.User{})
p.RegisterSchemaFromType("CreateOrganizationRequest", organizations.CreateOrganizationRequest{})
func (*Plugin) RegisterSecurityScheme ¶
func (p *Plugin) RegisterSecurityScheme(name string, scheme *SecurityScheme)
RegisterSecurityScheme adds a custom security scheme.
func (*Plugin) RegisterTag ¶
RegisterTag adds a tag for grouping operations.
func (*Plugin) RequiresTables ¶
RequiresTables returns required database tables.
func (*Plugin) UpdateSpec ¶
func (p *Plugin) UpdateSpec(metadata []core.RouteMetadata)
UpdateSpec updates the OpenAPI spec with route metadata.
type RequestBody ¶
type RequestBody struct {
Description string `json:"description,omitempty"`
Content map[string]MediaType `json:"content"`
Required bool `json:"required,omitempty"`
}
RequestBody describes a single request body.
type Response ¶
type Response struct {
Description string `json:"description"`
Content map[string]MediaType `json:"content,omitempty"`
Headers map[string]*Header `json:"headers,omitempty"`
}
Response describes a single response from an API operation.
type Schema ¶
type Schema struct {
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Properties map[string]*Schema `json:"properties,omitempty"`
Required []string `json:"required,omitempty"`
Items *Schema `json:"items,omitempty"`
Enum []any `json:"enum,omitempty"`
Example any `json:"example,omitempty"`
Ref string `json:"$ref,omitempty"`
AdditionalProperties any `json:"additionalProperties,omitempty"`
// Validation constraints
MinLength *int `json:"minLength,omitempty"`
MaxLength *int `json:"maxLength,omitempty"`
Pattern string `json:"pattern,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
MinItems *int `json:"minItems,omitempty"`
MaxItems *int `json:"maxItems,omitempty"`
}
Schema represents a JSON Schema object.
func ArraySchema ¶
ArraySchema creates an array schema.
func BooleanSchema ¶
BooleanSchema creates a boolean schema.
func DateTimeSchema ¶
DateTimeSchema creates a date-time string schema.
func EmailSchema ¶
EmailSchema creates an email string schema.
func GenerateSchema ¶
GenerateSchema creates an OpenAPI schema from a Go struct instance using reflection.
This function analyzes the struct's type information to automatically generate a JSON Schema compatible with OpenAPI 3.0.
Schema Generation:
- Inspect struct fields and types
- Parse JSON tags for field names
- Parse validation tags for constraints
- Determine required fields (non-omitempty, validation:"Required")
- Generate nested schemas for complex types
Supported Types:
- Primitives: string, int, bool, float
- Complex: struct, array, map
- Special: time.Time (date-time format)
Validation Tags:
- validation:"Required" -> required field
- validation:"Length(3,50)" -> minLength/maxLength
- validation:"Min(1),Max(100)" -> minimum/maximum
- validation:"Match(^[a-z]+$)" -> pattern
Parameters:
- v: Go struct instance or pointer to struct
Returns:
- *Schema: OpenAPI schema with properties and constraints
Example:
type User struct {
Name string `json:"name" validation:"Required,Length(1,100)"`
Email string `json:"email" validation:"Required,Match(^.+@.+$)"`
}
schema := GenerateSchema(User{})
func IntegerSchema ¶
IntegerSchema creates an integer schema.
func ObjectSchema ¶
ObjectSchema creates an object schema.
func StringSchema ¶
StringSchema creates a string schema.
func UUIDSchema ¶
UUIDSchema creates a UUID string schema.
type SecurityRequirement ¶
SecurityRequirement lists required security schemes to execute an operation.
type SecurityScheme ¶
type SecurityScheme struct {
Type string `json:"type"` // "apiKey", "http", "oauth2", "openIdConnect"
Description string `json:"description,omitempty"`
Name string `json:"name,omitempty"` // For apiKey
In string `json:"in,omitempty"` // For apiKey: "query", "header", "cookie"
Scheme string `json:"scheme,omitempty"` // For http: "bearer", "basic"
BearerFormat string `json:"bearerFormat,omitempty"` // For http bearer
Flows *OAuthFlows `json:"flows,omitempty"` // For oauth2
OpenIDConnectURL string `json:"openIdConnectUrl,omitempty"` // For openIdConnect
}
SecurityScheme defines a security scheme that can be used by operations.
type Server ¶
type Server struct {
URL string `json:"url"`
Description string `json:"description,omitempty"`
Variables map[string]ServerVariable `json:"variables,omitempty"`
}
Server represents a server URL.
type ServerVariable ¶
type ServerVariable struct {
Enum []string `json:"enum,omitempty"`
Default string `json:"Default"`
Description string `json:"description,omitempty"`
}
ServerVariable represents a server URL template variable.
type Spec ¶
type Spec struct {
OpenAPI string `json:"openapi"` // OpenAPI version (3.0.3)
Info Info `json:"info"` // API metadata
Servers []Server `json:"servers,omitempty"` // Server URLs
Paths map[string]*PathItem `json:"paths"` // API endpoints
Components *Components `json:"components,omitempty"` // Reusable components
Security []SecurityRequirement `json:"security,omitempty"` // Global security
Tags []Tag `json:"tags,omitempty"` // Endpoint tags
}
Spec represents an OpenAPI 3.0 specification document.
This is the root object of an OpenAPI 3.0 document, containing all metadata, paths, components, and security definitions.
Spec Structure:
- OpenAPI: Version ("3.0.3")
- Info: API metadata (title, version, description)
- Servers: API server URLs (dev, staging, production)
- Paths: All API endpoints and operations
- Components: Reusable schemas, security schemes
- Security: Global security requirements
- Tags: Endpoint categorization
func (*Spec) AddSecurityScheme ¶
func (s *Spec) AddSecurityScheme(name string, scheme *SecurityScheme)
AddSecurityScheme adds a security scheme component.