Documentation
¶
Index ¶
- Variables
- func CamelCaseToSnakeCase(str string) string
- func CleanTypeName(typeName string) string
- func ConvertToOpenAPIMethod(method string) string
- func ConvertToOpenAPIPath(path string) string
- func ExtractHandlerBaseName(handlerName string, stripSuffixes bool) string
- func ExtractValidationFromStructField(field reflect.StructField) map[string]string
- func FormatStatusCode(code int) string
- func GenerateDescription(method, path, handlerName string) string
- func GenerateTags(method, path, handlerName string) []string
- func GetHandlerName(handler interface{}) string
- func GetSystemFields() []string
- func HasSpec(version string) bool
- func ListSpecVersions() []string
- func NormalizePathSegment(segment string) string
- func ParseValidationTags(tag string) map[string]string
- func SetGlobalVersionManager(vm *APIVersionManager)
- func SnakeCaseToKebabCase(str string) string
- func ValidateAuthInfo(auth *AuthInfo) []string
- func ValidateConfiguration(config *APIDocsConfig) []string
- func ValidateEndpoint(endpoint *APIEndpoint) []string
- func ValidateSpecFile(specPath string, expectedVersion string) error
- func ValidateSpecs(specsDir string, versions []string) error
- func ValidateVersionString(version string) error
- type APIDocs
- type APIDocsConfig
- type APIEndpoint
- type APIRegistry
- func (r *APIRegistry) BatchRegisterRoutes(routes []RouteDefinition)
- func (r *APIRegistry) ClearEndpoints()
- func (r *APIRegistry) GetDocs() *APIDocs
- func (r *APIRegistry) GetDocsWithComponents() *APIDocs
- func (r *APIRegistry) GetEndpoint(method, path string) (*APIEndpoint, bool)
- func (r *APIRegistry) GetEndpointCount() int
- func (r *APIRegistry) GetEndpointsByTag(tag string) []APIEndpoint
- func (r *APIRegistry) GetEndpointsInternal() []APIEndpoint
- func (r *APIRegistry) GetRegisteredEndpoints() []APIEndpoint
- func (r *APIRegistry) GetVersion() string
- func (r *APIRegistry) RegisterEndpoint(endpoint APIEndpoint)
- func (r *APIRegistry) RegisterExplicitRoute(endpoint APIEndpoint)
- func (r *APIRegistry) RegisterRoute(method, path string, handler func(*core.RequestEvent) error, ...)
- func (r *APIRegistry) SetServers(servers []*OpenAPIServer)
- func (r *APIRegistry) SetVersion(version string)
- func (r *APIRegistry) UpdateConfig(config *APIDocsConfig)
- type APIVersionManager
- func GetGlobalVersionManager() *APIVersionManager
- func InitializeVersionManager(versions map[string]*APIDocsConfig, defaultVersion string) *APIVersionManager
- func InitializeVersionedSystem(versions map[string]*APIDocsConfig, defaultVersion string) *APIVersionManager
- func InitializeVersionedSystemWithRoutes(versions map[string]*VersionSetup, defaultVersion string) *APIVersionManager
- func NewAPIVersionManager() *APIVersionManager
- func NewAPIVersionManagerWithDefault(defaultVersion string) *APIVersionManager
- func (vm *APIVersionManager) BuildDebugData() map[string]any
- func (vm *APIVersionManager) GetAllVersions() []string
- func (vm *APIVersionManager) GetAllVersionsInfo() ([]*VersionInfo, error)
- func (vm *APIVersionManager) GetDefaultVersion() string
- func (vm *APIVersionManager) GetVersionConfig(version string) (*APIDocsConfig, error)
- func (vm *APIVersionManager) GetVersionInfo(version string) (*VersionInfo, error)
- func (vm *APIVersionManager) GetVersionOpenAPI(c *core.RequestEvent, version string) error
- func (vm *APIVersionManager) GetVersionOpenAPIPublic(c *core.RequestEvent, version string) error
- func (vm *APIVersionManager) GetVersionRegistry(version string) (*APIRegistry, error)
- func (vm *APIVersionManager) GetVersionRouter(version string, e *core.ServeEvent) (*VersionedAPIRouter, error)
- func (vm *APIVersionManager) GetVersionSchemaConfig(c *core.RequestEvent, version string) error
- func (vm *APIVersionManager) NewDocsOnlyVersionRouter(version string) (*VersionedAPIRouter, error)
- func (vm *APIVersionManager) RegisterAllVersionRoutes(e *core.ServeEvent) error
- func (vm *APIVersionManager) RegisterAllVersionRoutesForDocs() error
- func (vm *APIVersionManager) RegisterVersion(version string, config *APIDocsConfig) error
- func (vm *APIVersionManager) RegisterVersionRoutes(version string, e *core.ServeEvent) error
- func (vm *APIVersionManager) RegisterWithServer(app core.App)
- func (vm *APIVersionManager) RemoveVersion(version string) error
- func (vm *APIVersionManager) ServeSwaggerUI(c *core.RequestEvent, version string) error
- func (vm *APIVersionManager) SetDefaultVersion(version string) error
- func (vm *APIVersionManager) SetVersionRouteRegistrar(version string, registrar func(*VersionedAPIRouter)) error
- func (vm *APIVersionManager) SetVersionRouteRegistrars(registrars map[string]func(*VersionedAPIRouter)) error
- func (vm *APIVersionManager) ValidateRouteRegistrars() error
- func (vm *APIVersionManager) VersionsHandler(c *core.RequestEvent) error
- type ASTHandlerInfo
- type ASTParser
- func (p *ASTParser) ClearCache()
- func (p *ASTParser) DiscoverSourceFiles() error
- func (p *ASTParser) EnhanceEndpoint(endpoint *APIEndpoint) error
- func (p *ASTParser) GetAllHandlers() map[string]*ASTHandlerInfo
- func (p *ASTParser) GetAllStructs() map[string]*StructInfo
- func (p *ASTParser) GetHandlerByName(name string) (*ASTHandlerInfo, bool)
- func (p *ASTParser) GetHandlerDescription(handlerName string) string
- func (p *ASTParser) GetHandlerTags(handlerName string) []string
- func (p *ASTParser) GetParseErrors() []ParseError
- func (p *ASTParser) GetStructByName(name string) (*StructInfo, bool)
- func (p *ASTParser) GetStructsForFinding() map[string]*StructInfo
- func (p *ASTParser) ParseFile(filename string) error
- type ASTParserInterface
- type AuthInfo
- type AuthPattern
- type CRUDHandlers
- type DefaultLogger
- type Documentation
- type FieldInfo
- type FileParseResult
- type HandlerInfo
- type Logger
- type MapKeyAdd
- type MiddlewareAnalyzer
- type OpenAPICallback
- type OpenAPIComponents
- type OpenAPIContact
- type OpenAPIDiscriminator
- type OpenAPIEncoding
- type OpenAPIEndpointSchema
- type OpenAPIExample
- type OpenAPIExternalDocs
- type OpenAPIHeader
- type OpenAPIInfo
- type OpenAPILicense
- type OpenAPILink
- type OpenAPIMediaType
- type OpenAPIOAuthFlow
- type OpenAPIOAuthFlows
- type OpenAPIOperation
- type OpenAPIParameter
- type OpenAPIPathItem
- type OpenAPIRequestBody
- type OpenAPIResponse
- type OpenAPISchema
- type OpenAPISchemaBuilder
- type OpenAPISecurityScheme
- type OpenAPIServer
- type OpenAPIServerVariable
- type OpenAPITag
- type ParamInfo
- type ParseError
- type PathAnalyzer
- type PocketBasePatterns
- type PrefixedRouter
- func (pr *PrefixedRouter) CRUD(resource string, handlers CRUDHandlers, authMiddleware ...interface{})
- func (pr *PrefixedRouter) DELETE(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
- func (pr *PrefixedRouter) GET(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
- func (pr *PrefixedRouter) PATCH(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
- func (pr *PrefixedRouter) POST(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
- func (pr *PrefixedRouter) PUT(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
- type RegistryHelper
- type RequestPattern
- type RequestResponseAnalyzer
- type ResponsePattern
- type RouteAnalysis
- type RouteAnalyzer
- type RouteDefinition
- type RouteRegistrar
- type SchemaAnalysisResult
- type SchemaConfig
- type SchemaConversionResult
- type SchemaGenerator
- func (sg *SchemaGenerator) AnalyzeRequestSchema(endpoint *APIEndpoint) (*OpenAPISchema, error)
- func (sg *SchemaGenerator) AnalyzeResponseSchema(endpoint *APIEndpoint) (*OpenAPISchema, error)
- func (sg *SchemaGenerator) AnalyzeSchemaFromPath(method, path string) (*SchemaAnalysisResult, error)
- func (sg *SchemaGenerator) GenerateComponentSchemas() *OpenAPIComponents
- func (sg *SchemaGenerator) GetOpenAPIEndpointSchema(endpoint *APIEndpoint) (*OpenAPIEndpointSchema, error)
- type SchemaGeneratorInterface
- type SchemaPattern
- type SourceLocation
- type SpecGenerator
- type StructInfo
- type TypeInfo
- type TypeSchemaBuilder
- type TypeValidator
- type ValidationExtractor
- type VersionConfigProvider
- type VersionInfo
- type VersionManagerInitializer
- type VersionSetup
- type VersionedAPIRouter
- func (vr *VersionedAPIRouter) DELETE(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
- func (vr *VersionedAPIRouter) GET(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
- func (vr *VersionedAPIRouter) GetRegistry() *APIRegistry
- func (vr *VersionedAPIRouter) GetVersion() string
- func (vr *VersionedAPIRouter) GetVersionManager() *APIVersionManager
- func (vr *VersionedAPIRouter) PATCH(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
- func (vr *VersionedAPIRouter) POST(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
- func (vr *VersionedAPIRouter) PUT(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
- func (vr *VersionedAPIRouter) SetPrefix(prefix string) *PrefixedRouter
- type VersionedRouteChain
Examples ¶
- APIRegistry
- APIRegistry (WithAST)
- APIVersionManager
- ASTParser
- ASTParser.DiscoverSourceFiles
- AnalyzeHandler
- CamelCaseToSnakeCase
- CleanTypeName
- ConvertToOpenAPIPath
- GenerateDescription
- GenerateTags
- InitializeVersionedSystem
- RouteAnalyzer
- RouteAnalyzer.AnalyzeHandler
- SchemaGenerator
- SchemaGenerator.GenerateComponentSchemas
- ValidateEndpoint
- VersionedAPIRouter
Constants ¶
This section is empty.
Variables ¶
var ( StringSchema = &OpenAPISchema{Type: "string"} IntegerSchema = &OpenAPISchema{Type: "integer"} NumberSchema = &OpenAPISchema{Type: "number"} BooleanSchema = &OpenAPISchema{Type: "boolean"} ArraySchema = &OpenAPISchema{Type: "array"} ObjectSchema = &OpenAPISchema{Type: "object"} DateTimeSchema = &OpenAPISchema{Type: "string", Format: "date-time"} DateSchema = &OpenAPISchema{Type: "string", Format: "date"} EmailSchema = &OpenAPISchema{Type: "string", Format: "email"} UUIDSchema = &OpenAPISchema{Type: "string", Format: "uuid"} URISchema = &OpenAPISchema{Type: "string", Format: "uri"} PocketBaseRecordSchema = &OpenAPISchema{ Type: "object", Properties: map[string]*OpenAPISchema{ "id": {Type: "string", Description: "Record ID"}, "created": {Type: "string", Format: "date-time", Description: "Creation timestamp"}, "updated": {Type: "string", Format: "date-time", Description: "Last update timestamp"}, }, Required: []string{"id", "created", "updated"}, } ErrorResponseSchema = &OpenAPISchema{ Type: "object", Properties: map[string]*OpenAPISchema{ "code": {Type: "integer", Description: "Error code"}, "message": {Type: "string", Description: "Error message"}, "data": {Type: "object", Description: "Additional error data"}, }, Required: []string{"code", "message"}, } )
Functions ¶
func CamelCaseToSnakeCase ¶
CamelCaseToSnakeCase converts camelCase to snake_case
Example ¶
result := CamelCaseToSnakeCase("getUserProfile")
fmt.Println(result)
Output: get_user_profile
func CleanTypeName ¶
CleanTypeName cleans and normalizes type names for consistent usage
Example ¶
result := CleanTypeName("*[]github.com/test/models.User")
fmt.Println(result)
Output: User
func ConvertToOpenAPIMethod ¶
ConvertToOpenAPIMethod converts HTTP method to OpenAPI format
func ConvertToOpenAPIPath ¶
ConvertToOpenAPIPath converts path to OpenAPI format
Example ¶
result := ConvertToOpenAPIPath("/users/:id/posts/:postId")
fmt.Println(result)
Output: /users/{id}/posts/{postId}
func ExtractHandlerBaseName ¶
ExtractHandlerBaseName extracts a clean base name from handler function Consolidates ExtractBaseNameFromHandler and ExtractHandlerNameFromPath
func ExtractValidationFromStructField ¶
func ExtractValidationFromStructField(field reflect.StructField) map[string]string
ExtractValidationFromStructField extracts validation information from a struct field
func FormatStatusCode ¶
FormatStatusCode formats an HTTP status code with description
func GenerateDescription ¶
GenerateDescription generates descriptions from various sources Consolidates DescriptionFromHandlerName, DescriptionFromPath, GenerateAPIDescription
Example ¶
desc := GenerateDescription("GET", "/api/users/{id}", "getUserHandler")
fmt.Println(desc)
Output: Get User
func GenerateTags ¶
GenerateTags generates tags from multiple sources Consolidates GenerateTags, generateTagsFromPath, generateTagsFromHandler
Example ¶
tags := GenerateTags("POST", "/api/v1/users", "createUserHandler")
for i, tag := range tags {
fmt.Println("Tag", i, ":", tag)
}
Output: Tag 0 : api Tag 1 : v1 Tag 2 : users Tag 3 : create Tag 4 : user Tag 5 : post
func GetHandlerName ¶
func GetHandlerName(handler interface{}) string
GetHandlerName extracts the name of a handler function using reflection
func GetSystemFields ¶
func GetSystemFields() []string
GetSystemFields disabled - no system fields added
func HasSpec ¶
HasSpec returns true if a spec exists for the provided version on disk. If PB_EXT_OPENAPI_SPECS_DIR is set, specs are read from that directory. If PB_EXT_DISABLE_OPENAPI_SPECS is truthy, this always returns false.
func ListSpecVersions ¶
func ListSpecVersions() []string
ListSpecVersions returns discovered versions in stable sorted order from disk. If PB_EXT_OPENAPI_SPECS_DIR is set, specs are read from that directory. If PB_EXT_DISABLE_OPENAPI_SPECS is truthy, this returns an empty list.
func NormalizePathSegment ¶
NormalizePathSegment normalizes a path segment for consistent usage
func ParseValidationTags ¶
ParseValidationTags parses struct tag validation rules
func SetGlobalVersionManager ¶
func SetGlobalVersionManager(vm *APIVersionManager)
SetGlobalVersionManager sets the global version manager
func SnakeCaseToKebabCase ¶
SnakeCaseToKebabCase converts snake_case to kebab-case
func ValidateAuthInfo ¶
ValidateAuthInfo validates authentication information
func ValidateConfiguration ¶
func ValidateConfiguration(config *APIDocsConfig) []string
ValidateConfiguration validates an API documentation configuration
func ValidateEndpoint ¶
func ValidateEndpoint(endpoint *APIEndpoint) []string
ValidateEndpoint performs basic validation on an API endpoint
Example ¶
endpoint := &APIEndpoint{
Method: "GET",
Path: "/api/users",
}
errors := ValidateEndpoint(endpoint)
if len(errors) == 0 {
fmt.Println("Endpoint is valid")
} else {
for _, err := range errors {
fmt.Println("Error:", err)
}
}
Output: Endpoint is valid
func ValidateSpecFile ¶
func ValidateSpecs ¶
func ValidateVersionString ¶
ValidateVersionString validates that a version string is valid
Types ¶
type APIDocs ¶
type APIDocs struct {
OpenAPI string `json:"openapi"`
Info *OpenAPIInfo `json:"info"`
Servers []*OpenAPIServer `json:"servers,omitempty"`
Paths map[string]*OpenAPIPathItem `json:"paths"`
Components *OpenAPIComponents `json:"components,omitempty"`
Security []map[string][]string `json:"security,omitempty"`
Tags []*OpenAPITag `json:"tags,omitempty"`
ExternalDocs *OpenAPIExternalDocs `json:"externalDocs,omitempty"`
// contains filtered or unexported fields
}
APIDocs holds all API documentation in OpenAPI 3.0 format
type APIDocsConfig ¶
type APIDocsConfig struct {
Title string `json:"title"`
Version string `json:"version"`
Description string `json:"description"`
Status string `json:"status,omitempty"` // "stable", "development", "deprecated", "beta", etc.
BaseURL string `json:"base_url"`
Enabled bool `json:"enabled"`
ContactName string `json:"contact_name,omitempty"`
ContactEmail string `json:"contact_email,omitempty"`
ContactURL string `json:"contact_url,omitempty"`
LicenseName string `json:"license_name,omitempty"`
LicenseURL string `json:"license_url,omitempty"`
TermsOfService string `json:"terms_of_service,omitempty"`
ExternalDocsURL string `json:"external_docs_url,omitempty"`
ExternalDocsDesc string `json:"external_docs_desc,omitempty"`
PublicSwagger bool `json:"public_swagger,omitempty"`
}
APIDocsConfig holds configuration for the API documentation system
func DefaultAPIDocsConfig ¶
func DefaultAPIDocsConfig() *APIDocsConfig
DefaultAPIDocsConfig returns a default configuration
type APIEndpoint ¶
type APIEndpoint struct {
Method string `json:"method"`
Path string `json:"path"`
Description string `json:"description"`
Request *OpenAPISchema `json:"request,omitempty"`
Response *OpenAPISchema `json:"response,omitempty"`
Auth *AuthInfo `json:"auth,omitempty"`
Tags []string `json:"tags,omitempty"`
Handler string `json:"handler_name,omitempty"`
Parameters []*ParamInfo `json:"parameters,omitempty"`
}
APIEndpoint represents a single API endpoint documentation
type APIRegistry ¶
type APIRegistry struct {
// contains filtered or unexported fields
}
APIRegistry manages automatic API endpoint documentation with clean separation of concerns
Example ¶
Example function showing how to use the registry
// Create a new registry
registry := NewAPIRegistry(DefaultAPIDocsConfig(), nil, nil)
// Register an endpoint
endpoint := APIEndpoint{
Method: "GET",
Path: "/api/users",
Description: "Get all users",
Tags: []string{"users", "public"},
}
registry.RegisterEndpoint(endpoint)
// Get the endpoint back
retrieved, exists := registry.GetEndpoint("GET", "/api/users")
if exists {
fmt.Printf("Found endpoint: %s %s\n", retrieved.Method, retrieved.Path)
}
Output: Found endpoint: GET /api/users
Example (WithAST) ¶
Example function showing registry with AST enhancement
astParser := NewMockASTParser()
registry := NewAPIRegistry(DefaultAPIDocsConfig(), astParser, nil)
// Add mock handler info
handlerInfo := &ASTHandlerInfo{
APIDescription: "Enhanced by AST",
APITags: []string{"enhanced", "ast"},
}
astParser.AddMockHandler("testHandler", handlerInfo)
// Register endpoint
endpoint := APIEndpoint{
Method: "POST",
Path: "/api/test",
Handler: "testHandler",
}
registry.RegisterExplicitRoute(endpoint)
// The endpoint should be enhanced with AST data
docs := registry.GetDocs()
fmt.Printf("Enhanced endpoint description: %s\n", docs.endpoints[0].Description)
Output: Enhanced endpoint description: Enhanced by AST
func NewAPIRegistry ¶
func NewAPIRegistry(config *APIDocsConfig, astParser ASTParserInterface, schemaGenerator SchemaGeneratorInterface) *APIRegistry
NewAPIRegistry creates a new API documentation registry with dependency injection
func (*APIRegistry) BatchRegisterRoutes ¶
func (r *APIRegistry) BatchRegisterRoutes(routes []RouteDefinition)
BatchRegisterRoutes registers multiple routes at once
func (*APIRegistry) ClearEndpoints ¶
func (r *APIRegistry) ClearEndpoints()
ClearEndpoints removes all registered endpoints
func (*APIRegistry) GetDocs ¶
func (r *APIRegistry) GetDocs() *APIDocs
GetDocs returns the current API documentation
func (*APIRegistry) GetDocsWithComponents ¶
func (r *APIRegistry) GetDocsWithComponents() *APIDocs
GetDocsWithComponents returns documentation with generated component schemas. Only includes component schemas that are actually referenced by this version's endpoints. The assembled spec is cached and only regenerated when endpoints change.
func (*APIRegistry) GetEndpoint ¶
func (r *APIRegistry) GetEndpoint(method, path string) (*APIEndpoint, bool)
GetEndpoint retrieves a specific endpoint by method and path
func (*APIRegistry) GetEndpointCount ¶
func (r *APIRegistry) GetEndpointCount() int
GetEndpointCount returns the number of registered endpoints
func (*APIRegistry) GetEndpointsByTag ¶
func (r *APIRegistry) GetEndpointsByTag(tag string) []APIEndpoint
GetEndpointsByTag returns all endpoints that have the specified tag
func (*APIRegistry) GetEndpointsInternal ¶
func (r *APIRegistry) GetEndpointsInternal() []APIEndpoint
GetEndpointsInternal returns the internal endpoints list (for backwards compatibility)
func (*APIRegistry) GetRegisteredEndpoints ¶
func (r *APIRegistry) GetRegisteredEndpoints() []APIEndpoint
GetRegisteredEndpoints returns all currently registered endpoints
func (*APIRegistry) GetVersion ¶
func (r *APIRegistry) GetVersion() string
GetVersion returns the API version associated with this registry.
func (*APIRegistry) RegisterEndpoint ¶
func (r *APIRegistry) RegisterEndpoint(endpoint APIEndpoint)
RegisterEndpoint manually registers an API endpoint
func (*APIRegistry) RegisterExplicitRoute ¶
func (r *APIRegistry) RegisterExplicitRoute(endpoint APIEndpoint)
RegisterExplicitRoute registers a route with explicit information (no inference)
func (*APIRegistry) RegisterRoute ¶
func (r *APIRegistry) RegisterRoute(method, path string, handler func(*core.RequestEvent) error, middlewares ...interface{})
RegisterRoute explicitly registers a route with optional middleware
func (*APIRegistry) SetServers ¶
func (r *APIRegistry) SetServers(servers []*OpenAPIServer)
SetServers sets the OpenAPI servers and derives a path prefix to strip from registered paths. When a server URL ends with a path (e.g., http://host/api/v1), registered paths like /api/v1/todos will be stored as /todos in the spec, since the server URL already includes the prefix.
func (*APIRegistry) SetVersion ¶
func (r *APIRegistry) SetVersion(version string)
SetVersion sets the API version associated with this registry.
func (*APIRegistry) UpdateConfig ¶
func (r *APIRegistry) UpdateConfig(config *APIDocsConfig)
UpdateConfig updates the registry configuration
type APIVersionManager ¶
type APIVersionManager struct {
// contains filtered or unexported fields
}
APIVersionManager manages multiple API versions with separate registries
Example ¶
// Create version manager
vm := NewAPIVersionManager()
// Register a version
config := &APIDocsConfig{
Title: "My API",
Version: "1.0.0",
Description: "First version of my API",
BaseURL: "/api/v1",
Enabled: true,
}
vm.RegisterVersion("v1", config)
vm.SetDefaultVersion("v1")
// Get version info
info, _ := vm.GetVersionInfo("v1")
fmt.Printf("Version: %s, Title: %s\n", info.Version, info.Config.Title)
Output: Version: v1, Title: My API
func GetGlobalVersionManager ¶
func GetGlobalVersionManager() *APIVersionManager
GetGlobalVersionManager returns the global version manager instance
func InitializeVersionManager ¶
func InitializeVersionManager(versions map[string]*APIDocsConfig, defaultVersion string) *APIVersionManager
InitializeVersionManager creates and configures a version manager
func InitializeVersionedSystem ¶
func InitializeVersionedSystem(versions map[string]*APIDocsConfig, defaultVersion string) *APIVersionManager
InitializeVersionedSystem initializes a versioned documentation system
Example ¶
configs := map[string]*APIDocsConfig{
"v1": {
Title: "API v1",
Version: "1.0.0",
Description: "Stable API",
Status: "stable",
BaseURL: "/api/v1",
Enabled: true,
},
"v2": {
Title: "API v2",
Version: "2.0.0",
Description: "Beta API",
Status: "beta",
BaseURL: "/api/v2",
Enabled: true,
},
}
vm := InitializeVersionedSystem(configs, "v1")
versions := vm.GetAllVersions()
fmt.Printf("Available versions: %v\n", versions)
Output: Available versions: [v1 v2]
func InitializeVersionedSystemWithRoutes ¶
func InitializeVersionedSystemWithRoutes(versions map[string]*VersionSetup, defaultVersion string) *APIVersionManager
InitializeVersionedSystemWithRoutes creates a version manager with both configs and route registrars in one call This eliminates the need for separate InitializeVersionedSystem + SetVersionRouteRegistrars calls
func NewAPIVersionManager ¶
func NewAPIVersionManager() *APIVersionManager
NewAPIVersionManager creates a new version manager
func NewAPIVersionManagerWithDefault ¶
func NewAPIVersionManagerWithDefault(defaultVersion string) *APIVersionManager
NewAPIVersionManagerWithDefault creates a version manager with a default version
func (*APIVersionManager) BuildDebugData ¶
func (vm *APIVersionManager) BuildDebugData() map[string]any
BuildDebugData returns a comprehensive JSON-friendly debug dump of the entire API documentation pipeline. This covers:
- AST parsing: discovered structs, type aliases, handlers
- Handler analysis: variables, variable expressions, request/response types and schemas
- Per-version: registered endpoints, component schemas, final OpenAPI output
Served at /api/docs/debug/ast
func (*APIVersionManager) GetAllVersions ¶
func (vm *APIVersionManager) GetAllVersions() []string
GetAllVersions returns all registered versions
func (*APIVersionManager) GetAllVersionsInfo ¶
func (vm *APIVersionManager) GetAllVersionsInfo() ([]*VersionInfo, error)
GetAllVersionsInfo returns information about all versions
func (*APIVersionManager) GetDefaultVersion ¶
func (vm *APIVersionManager) GetDefaultVersion() string
GetDefaultVersion returns the default version
func (*APIVersionManager) GetVersionConfig ¶
func (vm *APIVersionManager) GetVersionConfig(version string) (*APIDocsConfig, error)
GetVersionConfig returns the configuration for a specific version
func (*APIVersionManager) GetVersionInfo ¶
func (vm *APIVersionManager) GetVersionInfo(version string) (*VersionInfo, error)
GetVersionInfo returns detailed information about a specific version
func (*APIVersionManager) GetVersionOpenAPI ¶
func (vm *APIVersionManager) GetVersionOpenAPI(c *core.RequestEvent, version string) error
GetVersionOpenAPI returns the complete OpenAPI schema for a specific version
func (*APIVersionManager) GetVersionOpenAPIPublic ¶
func (vm *APIVersionManager) GetVersionOpenAPIPublic(c *core.RequestEvent, version string) error
GetVersionOpenAPIPublic returns the OpenAPI spec without requiring authentication
func (*APIVersionManager) GetVersionRegistry ¶
func (vm *APIVersionManager) GetVersionRegistry(version string) (*APIRegistry, error)
GetVersionRegistry returns the registry for a specific version
func (*APIVersionManager) GetVersionRouter ¶
func (vm *APIVersionManager) GetVersionRouter(version string, e *core.ServeEvent) (*VersionedAPIRouter, error)
GetVersionRouter creates a versioned API router for the specified version
func (*APIVersionManager) GetVersionSchemaConfig ¶
func (vm *APIVersionManager) GetVersionSchemaConfig(c *core.RequestEvent, version string) error
GetVersionSchemaConfig returns the schema configuration for a specific version
func (*APIVersionManager) NewDocsOnlyVersionRouter ¶
func (vm *APIVersionManager) NewDocsOnlyVersionRouter(version string) (*VersionedAPIRouter, error)
NewDocsOnlyVersionRouter creates a versioned router bound only to docs registry state. It does not require a ServeEvent and should be used for build-time/spec generation flows.
func (*APIVersionManager) RegisterAllVersionRoutes ¶
func (vm *APIVersionManager) RegisterAllVersionRoutes(e *core.ServeEvent) error
RegisterAllVersionRoutes registers all version routes to a ServeEvent router and docs registries.
func (*APIVersionManager) RegisterAllVersionRoutesForDocs ¶
func (vm *APIVersionManager) RegisterAllVersionRoutesForDocs() error
RegisterAllVersionRoutesForDocs registers all version routes only to docs registries.
func (*APIVersionManager) RegisterVersion ¶
func (vm *APIVersionManager) RegisterVersion(version string, config *APIDocsConfig) error
RegisterVersion registers a new API version with its own registry
func (*APIVersionManager) RegisterVersionRoutes ¶
func (vm *APIVersionManager) RegisterVersionRoutes(version string, e *core.ServeEvent) error
RegisterVersionRoutes registers one version's routes either for serve (when e != nil) or docs-only (when e == nil).
func (*APIVersionManager) RegisterWithServer ¶
func (vm *APIVersionManager) RegisterWithServer(app core.App)
RegisterWithServer registers version management endpoints
func (*APIVersionManager) RemoveVersion ¶
func (vm *APIVersionManager) RemoveVersion(version string) error
RemoveVersion removes a version and its registry
func (*APIVersionManager) ServeSwaggerUI ¶
func (vm *APIVersionManager) ServeSwaggerUI(c *core.RequestEvent, version string) error
ServeSwaggerUI serves the Swagger UI HTML page for the given API version
func (*APIVersionManager) SetDefaultVersion ¶
func (vm *APIVersionManager) SetDefaultVersion(version string) error
SetDefaultVersion sets the default API version
func (*APIVersionManager) SetVersionRouteRegistrar ¶
func (vm *APIVersionManager) SetVersionRouteRegistrar(version string, registrar func(*VersionedAPIRouter)) error
SetVersionRouteRegistrar sets or replaces the route registration callback for a version.
func (*APIVersionManager) SetVersionRouteRegistrars ¶
func (vm *APIVersionManager) SetVersionRouteRegistrars(registrars map[string]func(*VersionedAPIRouter)) error
SetVersionRouteRegistrars sets route registration callbacks for multiple versions.
func (*APIVersionManager) ValidateRouteRegistrars ¶
func (vm *APIVersionManager) ValidateRouteRegistrars() error
ValidateRouteRegistrars ensures every registered API version has a route registrar.
func (*APIVersionManager) VersionsHandler ¶
func (vm *APIVersionManager) VersionsHandler(c *core.RequestEvent) error
VersionsHandler returns list of all available API versions
type ASTHandlerInfo ¶
type ASTHandlerInfo struct {
Name string `json:"name"`
Package string `json:"package"`
RequestType string `json:"request_type"`
ResponseType string `json:"response_type"`
RequestSchema *OpenAPISchema `json:"request_schema,omitempty"`
ResponseSchema *OpenAPISchema `json:"response_schema,omitempty"`
OriginalResponseSchema *OpenAPISchema `json:"-"` // preserved copy before promotion to $ref
Parameters []*ParamInfo `json:"parameters,omitempty"`
UsesJSONDecode bool `json:"uses_json_decode"`
UsesJSONReturn bool `json:"uses_json_return"`
APIDescription string `json:"api_description"`
APITags []string `json:"api_tags"`
HTTPMethods []string `json:"http_methods"`
RoutePath string `json:"route_path,omitempty"`
Middleware []string `json:"middleware,omitempty"`
Documentation *Documentation `json:"documentation,omitempty"`
Complexity int `json:"complexity"`
SourceLocation *SourceLocation `json:"source_location,omitempty"`
Variables map[string]string `json:"variables,omitempty"`
VariableExprs map[string]ast.Expr `json:"-"`
MapAdditions map[string][]MapKeyAdd `json:"-"`
SliceAppendExprs map[string]ast.Expr `json:"-"`
AnonStructSchemas map[string]*OpenAPISchema `json:"-"` // inline struct schemas keyed by var name
// PocketBase-specific fields
RequiresAuth bool `json:"requires_auth"`
UsesBindBody bool `json:"uses_bind_body"`
UsesRequestInfo bool `json:"uses_request_info"`
DatabaseOperations []string `json:"database_operations,omitempty"`
AuthType string `json:"auth_type,omitempty"`
Collection string `json:"collection,omitempty"`
UsesEnrichRecords bool `json:"uses_enrich_records"`
}
ASTHandlerInfo contains comprehensive handler information
type ASTParser ¶
type ASTParser struct {
// contains filtered or unexported fields
}
ASTParser provides robust AST parsing with improved error handling and performance
Example ¶
// Create a new AST parser
parser := NewASTParser()
// Parse a specific file
err := parser.ParseFile("handlers.go")
if err != nil {
panic(err)
}
// Get all discovered handlers
handlers := parser.GetAllHandlers()
for _, handler := range handlers {
println("Handler:", handler.Name, "Description:", handler.APIDescription)
}
// Get a specific struct
userStruct, exists := parser.GetStructByName("User")
if userStruct != nil && exists {
println("Found User struct with", len(userStruct.Fields), "fields")
}
// Enhance an endpoint with AST information
endpoint := &APIEndpoint{
Method: "GET",
Path: "/users",
Handler: "getUsersHandler",
}
parser.EnhanceEndpoint(endpoint)
println("Enhanced endpoint description:", endpoint.Description)
func NewASTParser ¶
func NewASTParser() *ASTParser
NewASTParser creates a new simplified PocketBase-focused AST parser
func (*ASTParser) ClearCache ¶
func (p *ASTParser) ClearCache()
ClearCache clears all cached data (interface compatibility)
func (*ASTParser) DiscoverSourceFiles ¶
DiscoverSourceFiles finds and parses files with API_SOURCE directive, then follows local imports to parse struct definitions from imported packages.
Example ¶
// Create parser and auto-discover all API source files
parser := NewASTParser()
err := parser.DiscoverSourceFiles()
if err != nil {
panic(err)
}
// All files with // API_SOURCE directive have been parsed
handlers := parser.GetAllHandlers()
structs := parser.GetAllStructs()
println("Discovered", len(handlers), "handlers and", len(structs), "structs")
func (*ASTParser) EnhanceEndpoint ¶
func (p *ASTParser) EnhanceEndpoint(endpoint *APIEndpoint) error
EnhanceEndpoint enhances an endpoint with AST analysis
func (*ASTParser) GetAllHandlers ¶
func (p *ASTParser) GetAllHandlers() map[string]*ASTHandlerInfo
GetAllHandlers returns all parsed handlers
func (*ASTParser) GetAllStructs ¶
func (p *ASTParser) GetAllStructs() map[string]*StructInfo
GetAllStructs returns all parsed structs
func (*ASTParser) GetHandlerByName ¶
func (p *ASTParser) GetHandlerByName(name string) (*ASTHandlerInfo, bool)
GetHandlerByName returns a handler by name
func (*ASTParser) GetHandlerDescription ¶
GetHandlerDescription returns description for a handler
func (*ASTParser) GetHandlerTags ¶
GetHandlerTags returns tags for a handler
func (*ASTParser) GetParseErrors ¶
func (p *ASTParser) GetParseErrors() []ParseError
GetParseErrors returns parse errors (interface compatibility)
func (*ASTParser) GetStructByName ¶
func (p *ASTParser) GetStructByName(name string) (*StructInfo, bool)
GetStructByName returns a struct by name
func (*ASTParser) GetStructsForFinding ¶
func (p *ASTParser) GetStructsForFinding() map[string]*StructInfo
GetStructsForFinding returns all structs for searching operations (interface compatibility)
type ASTParserInterface ¶
type ASTParserInterface interface {
ParseFile(filename string) error
GetAllStructs() map[string]*StructInfo
GetAllHandlers() map[string]*ASTHandlerInfo
GetStructByName(name string) (*StructInfo, bool)
GetHandlerByName(name string) (*ASTHandlerInfo, bool)
GetParseErrors() []ParseError
ClearCache()
EnhanceEndpoint(endpoint *APIEndpoint) error
GetHandlerDescription(handlerName string) string
GetHandlerTags(handlerName string) []string
GetStructsForFinding() map[string]*StructInfo
}
ASTParserInterface defines the contract for AST parsing operations
type AuthInfo ¶
type AuthInfo struct {
Required bool `json:"required"`
Type string `json:"type"` // "guest_only", "auth", "superuser", "superuser_or_owner"
Collections []string `json:"collections,omitempty"` // For RequireAuth with specific collections
OwnerParam string `json:"owner_param,omitempty"` // For RequireSuperuserOrOwnerAuth
Description string `json:"description"`
Icon string `json:"icon"`
}
AuthInfo represents detailed authentication requirements for an API endpoint
type AuthPattern ¶
type AuthPattern struct {
Pattern string `json:"pattern"`
Required bool `json:"required"`
Description string `json:"description"`
}
AuthPattern defines a PocketBase authentication pattern
type CRUDHandlers ¶
type CRUDHandlers struct {
List func(*core.RequestEvent) error // GET /resource
Create func(*core.RequestEvent) error // POST /resource
Get func(*core.RequestEvent) error // GET /resource/{id}
Update func(*core.RequestEvent) error // PUT /resource/{id}
Patch func(*core.RequestEvent) error // PATCH /resource/{id}
Delete func(*core.RequestEvent) error // DELETE /resource/{id}
}
CRUDHandlers holds handler functions for CRUD operations
type DefaultLogger ¶
type DefaultLogger struct{}
DefaultLogger provides a no-op logger implementation
func (*DefaultLogger) Debug ¶
func (l *DefaultLogger) Debug(msg string, args ...interface{})
func (*DefaultLogger) Error ¶
func (l *DefaultLogger) Error(msg string, args ...interface{})
func (*DefaultLogger) Info ¶
func (l *DefaultLogger) Info(msg string, args ...interface{})
func (*DefaultLogger) Log ¶
func (l *DefaultLogger) Log(msg string)
func (*DefaultLogger) Warn ¶
func (l *DefaultLogger) Warn(msg string, args ...interface{})
type Documentation ¶
type Documentation struct {
Summary string `json:"summary"`
Description string `json:"description"`
Parameters map[string]string `json:"parameters,omitempty"`
Returns string `json:"returns,omitempty"`
Examples []string `json:"examples,omitempty"`
SeeAlso []string `json:"see_also,omitempty"`
Since string `json:"since,omitempty"`
Deprecated string `json:"deprecated,omitempty"`
Authors []string `json:"authors,omitempty"`
Tags []string `json:"tags,omitempty"`
}
Documentation contains extracted documentation information
type FieldInfo ¶
type FieldInfo struct {
Name string `json:"name"`
Type string `json:"type"`
JSONName string `json:"json_name"`
JSONOmitEmpty bool `json:"json_omit_empty"`
Required bool `json:"required"`
Validation map[string]string `json:"validation"`
Description string `json:"description"`
Example interface{} `json:"example,omitempty"`
Schema *OpenAPISchema `json:"schema"`
IsPointer bool `json:"is_pointer"`
IsEmbedded bool `json:"is_embedded"`
IsExported bool `json:"is_exported"`
DefaultValue interface{} `json:"default_value,omitempty"`
Constraints map[string]interface{} `json:"constraints,omitempty"`
SourceLocation *SourceLocation `json:"source_location,omitempty"`
}
FieldInfo contains detailed field information
type FileParseResult ¶
type FileParseResult struct {
ModTime time.Time
Structs map[string]*StructInfo
Handlers map[string]*ASTHandlerInfo
Imports map[string]string
Errors []ParseError
ParsedAt time.Time
}
FileParseResult stores parsing results with metadata
type HandlerInfo ¶
type HandlerInfo struct {
Name string `json:"name"`
Package string `json:"package"`
FullName string `json:"full_name"`
Description string `json:"description"`
}
HandlerInfo contains extracted handler information
func AnalyzeHandler ¶
func AnalyzeHandler(handler interface{}) *HandlerInfo
AnalyzeHandler provides comprehensive handler analysis
Example ¶
handler := func(c *core.RequestEvent) error {
return nil
}
info := AnalyzeHandler(handler)
fmt.Println("Handler Name:", info.Name)
fmt.Println("Description:", info.Description)
Output: Handler Name: func1 Description: Func1
type Logger ¶
type Logger interface {
Debug(msg string, args ...interface{})
Info(msg string, args ...interface{})
Warn(msg string, args ...interface{})
Error(msg string, args ...interface{})
}
Logger interface for structured logging
type MiddlewareAnalyzer ¶
type MiddlewareAnalyzer struct{}
MiddlewareAnalyzer provides utilities for analyzing middleware
func NewMiddlewareAnalyzer ¶
func NewMiddlewareAnalyzer() *MiddlewareAnalyzer
NewMiddlewareAnalyzer creates a new middleware analyzer
func (*MiddlewareAnalyzer) AnalyzeAuth ¶
func (ma *MiddlewareAnalyzer) AnalyzeAuth(middlewares []interface{}) *AuthInfo
AnalyzeAuth analyzes middleware to determine authentication requirements
type OpenAPICallback ¶
type OpenAPICallback map[string]*OpenAPIPathItem
OpenAPICallback represents an OpenAPI callback object
type OpenAPIComponents ¶
type OpenAPIComponents struct {
Schemas map[string]*OpenAPISchema `json:"schemas,omitempty"`
Responses map[string]*OpenAPIResponse `json:"responses,omitempty"`
Parameters map[string]*OpenAPIParameter `json:"parameters,omitempty"`
Examples map[string]*OpenAPIExample `json:"examples,omitempty"`
RequestBodies map[string]*OpenAPIRequestBody `json:"requestBodies,omitempty"`
Headers map[string]*OpenAPIHeader `json:"headers,omitempty"`
SecuritySchemes map[string]*OpenAPISecurityScheme `json:"securitySchemes,omitempty"`
Links map[string]*OpenAPILink `json:"links,omitempty"`
Callbacks map[string]*OpenAPICallback `json:"callbacks,omitempty"`
}
OpenAPIComponents represents an OpenAPI components object
type OpenAPIContact ¶
type OpenAPIContact struct {
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Email string `json:"email,omitempty"`
}
OpenAPIContact represents contact information in OpenAPI 3.0 spec
type OpenAPIDiscriminator ¶
type OpenAPIDiscriminator struct {
PropertyName string `json:"propertyName"`
Mapping map[string]string `json:"mapping,omitempty"`
}
OpenAPIDiscriminator represents an OpenAPI discriminator object
type OpenAPIEncoding ¶
type OpenAPIEncoding struct {
ContentType string `json:"contentType,omitempty"`
Headers map[string]*OpenAPIHeader `json:"headers,omitempty"`
Style string `json:"style,omitempty"`
Explode *bool `json:"explode,omitempty"`
AllowReserved *bool `json:"allowReserved,omitempty"`
}
OpenAPIEncoding represents an OpenAPI encoding object
type OpenAPIEndpointSchema ¶
type OpenAPIEndpointSchema struct {
Operation *OpenAPIOperation `json:"operation"`
Parameters []*OpenAPIParameter `json:"parameters,omitempty"`
RequestBody *OpenAPIRequestBody `json:"requestBody,omitempty"`
Responses map[string]*OpenAPIResponse `json:"responses"`
Security []map[string][]string `json:"security,omitempty"`
}
OpenAPIEndpointSchema represents a complete OpenAPI endpoint schema
type OpenAPIExample ¶
type OpenAPIExample struct {
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Value interface{} `json:"value,omitempty"`
ExternalValue string `json:"externalValue,omitempty"`
}
OpenAPIExample represents an OpenAPI example object
type OpenAPIExternalDocs ¶
type OpenAPIExternalDocs struct {
Description string `json:"description,omitempty"`
URL string `json:"url"`
}
OpenAPIExternalDocs represents an OpenAPI external documentation object
type OpenAPIHeader ¶
type OpenAPIHeader struct {
Description string `json:"description,omitempty"`
Required *bool `json:"required,omitempty"`
Deprecated *bool `json:"deprecated,omitempty"`
AllowEmptyValue *bool `json:"allowEmptyValue,omitempty"`
Style string `json:"style,omitempty"`
Explode *bool `json:"explode,omitempty"`
Schema *OpenAPISchema `json:"schema,omitempty"`
Content map[string]*OpenAPIMediaType `json:"content,omitempty"`
Example interface{} `json:"example,omitempty"`
Examples map[string]*OpenAPIExample `json:"examples,omitempty"`
}
OpenAPIHeader represents an OpenAPI header object
type OpenAPIInfo ¶
type OpenAPIInfo struct {
Title string `json:"title"`
Version string `json:"version"`
Description string `json:"description,omitempty"`
TermsOfService string `json:"termsOfService,omitempty"`
Contact *OpenAPIContact `json:"contact,omitempty"`
License *OpenAPILicense `json:"license,omitempty"`
}
OpenAPIInfo represents the info object in OpenAPI 3.0 spec
type OpenAPILicense ¶
OpenAPILicense represents license information in OpenAPI 3.0 spec
type OpenAPILink ¶
type OpenAPILink struct {
OperationRef string `json:"operationRef,omitempty"`
OperationId string `json:"operationId,omitempty"`
Parameters map[string]interface{} `json:"parameters,omitempty"`
RequestBody interface{} `json:"requestBody,omitempty"`
Description string `json:"description,omitempty"`
Server *OpenAPIServer `json:"server,omitempty"`
}
OpenAPILink represents an OpenAPI link object
type OpenAPIMediaType ¶
type OpenAPIMediaType struct {
Schema *OpenAPISchema `json:"schema,omitempty"`
Example interface{} `json:"example,omitempty"`
Examples map[string]*OpenAPIExample `json:"examples,omitempty"`
Encoding map[string]*OpenAPIEncoding `json:"encoding,omitempty"`
}
OpenAPIMediaType represents an OpenAPI media type object
type OpenAPIOAuthFlow ¶
type OpenAPIOAuthFlow struct {
AuthorizationUrl string `json:"authorizationUrl,omitempty"`
TokenUrl string `json:"tokenUrl,omitempty"`
RefreshUrl string `json:"refreshUrl,omitempty"`
Scopes map[string]string `json:"scopes"`
}
OpenAPIOAuthFlow represents an OpenAPI OAuth flow object
type OpenAPIOAuthFlows ¶
type OpenAPIOAuthFlows struct {
Implicit *OpenAPIOAuthFlow `json:"implicit,omitempty"`
Password *OpenAPIOAuthFlow `json:"password,omitempty"`
ClientCredentials *OpenAPIOAuthFlow `json:"clientCredentials,omitempty"`
AuthorizationCode *OpenAPIOAuthFlow `json:"authorizationCode,omitempty"`
}
OpenAPIOAuthFlows represents an OpenAPI OAuth flows object
type OpenAPIOperation ¶
type OpenAPIOperation struct {
Tags []string `json:"tags,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
ExternalDocs *OpenAPIExternalDocs `json:"externalDocs,omitempty"`
OperationId string `json:"operationId,omitempty"`
Parameters []*OpenAPIParameter `json:"parameters,omitempty"`
RequestBody *OpenAPIRequestBody `json:"requestBody,omitempty"`
Responses map[string]*OpenAPIResponse `json:"responses"`
Callbacks map[string]*OpenAPICallback `json:"callbacks,omitempty"`
Deprecated *bool `json:"deprecated,omitempty"`
Security []map[string][]string `json:"security,omitempty"`
Servers []*OpenAPIServer `json:"servers,omitempty"`
}
OpenAPIOperation represents an OpenAPI operation object
func ConvertHandlerInfoToOpenAPIOperation ¶
func ConvertHandlerInfoToOpenAPIOperation(handlerInfo *ASTHandlerInfo) *OpenAPIOperation
ConvertHandlerInfoToOpenAPIOperation converts an ASTHandlerInfo to an OpenAPI operation
type OpenAPIParameter ¶
type OpenAPIParameter struct {
Name string `json:"name"`
In string `json:"in"` // "query", "header", "path", "cookie"
Description string `json:"description,omitempty"`
Required *bool `json:"required,omitempty"`
Deprecated *bool `json:"deprecated,omitempty"`
AllowEmptyValue *bool `json:"allowEmptyValue,omitempty"`
Style string `json:"style,omitempty"`
Explode *bool `json:"explode,omitempty"`
Schema *OpenAPISchema `json:"schema,omitempty"`
Content map[string]*OpenAPIMediaType `json:"content,omitempty"`
Example interface{} `json:"example,omitempty"`
Examples map[string]*OpenAPIExample `json:"examples,omitempty"`
Ref string `json:"$ref,omitempty"`
}
OpenAPIParameter represents an OpenAPI parameter object
func ConvertParamInfoToOpenAPIParameter ¶
func ConvertParamInfoToOpenAPIParameter(paramInfo *ParamInfo) *OpenAPIParameter
ConvertParamInfoToOpenAPIParameter converts a ParamInfo to an OpenAPI parameter
type OpenAPIPathItem ¶
type OpenAPIPathItem struct {
Ref string `json:"$ref,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Get *OpenAPIOperation `json:"get,omitempty"`
Put *OpenAPIOperation `json:"put,omitempty"`
Post *OpenAPIOperation `json:"post,omitempty"`
Delete *OpenAPIOperation `json:"delete,omitempty"`
Options *OpenAPIOperation `json:"options,omitempty"`
Head *OpenAPIOperation `json:"head,omitempty"`
Patch *OpenAPIOperation `json:"patch,omitempty"`
Trace *OpenAPIOperation `json:"trace,omitempty"`
Servers []*OpenAPIServer `json:"servers,omitempty"`
Parameters []*OpenAPIParameter `json:"parameters,omitempty"`
}
OpenAPIPathItem represents an OpenAPI path item object
type OpenAPIRequestBody ¶
type OpenAPIRequestBody struct {
Description string `json:"description,omitempty"`
Content map[string]*OpenAPIMediaType `json:"content"`
Required *bool `json:"required,omitempty"`
Ref string `json:"$ref,omitempty"`
}
OpenAPIRequestBody represents an OpenAPI request body object
type OpenAPIResponse ¶
type OpenAPIResponse struct {
Description string `json:"description"`
Headers map[string]*OpenAPIHeader `json:"headers,omitempty"`
Content map[string]*OpenAPIMediaType `json:"content,omitempty"`
Links map[string]*OpenAPILink `json:"links,omitempty"`
Ref string `json:"$ref,omitempty"`
}
OpenAPIResponse represents an OpenAPI response object
type OpenAPISchema ¶
type OpenAPISchema struct {
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Default interface{} `json:"default,omitempty"`
Example interface{} `json:"example,omitempty"`
Examples map[string]*OpenAPIExample `json:"examples,omitempty"`
// Validation keywords
MultipleOf *float64 `json:"multipleOf,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
ExclusiveMaximum *bool `json:"exclusiveMaximum,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
ExclusiveMinimum *bool `json:"exclusiveMinimum,omitempty"`
MaxLength *int `json:"maxLength,omitempty"`
MinLength *int `json:"minLength,omitempty"`
Pattern string `json:"pattern,omitempty"`
MaxItems *int `json:"maxItems,omitempty"`
MinItems *int `json:"minItems,omitempty"`
UniqueItems *bool `json:"uniqueItems,omitempty"`
MaxProperties *int `json:"maxProperties,omitempty"`
MinProperties *int `json:"minProperties,omitempty"`
Required []string `json:"required,omitempty"`
Enum []interface{} `json:"enum,omitempty"`
// Object properties
Properties map[string]*OpenAPISchema `json:"properties,omitempty"`
AdditionalProperties interface{} `json:"additionalProperties,omitempty"` // bool or Schema
// Array items
Items *OpenAPISchema `json:"items,omitempty"`
// Composition
AllOf []*OpenAPISchema `json:"allOf,omitempty"`
OneOf []*OpenAPISchema `json:"oneOf,omitempty"`
AnyOf []*OpenAPISchema `json:"anyOf,omitempty"`
Not *OpenAPISchema `json:"not,omitempty"`
// Reference
Ref string `json:"$ref,omitempty"`
// Discriminator for inheritance
Discriminator *OpenAPIDiscriminator `json:"discriminator,omitempty"`
// Read/Write only
ReadOnly *bool `json:"readOnly,omitempty"`
WriteOnly *bool `json:"writeOnly,omitempty"`
// Deprecated
Deprecated *bool `json:"deprecated,omitempty"`
// External documentation
ExternalDocs *OpenAPIExternalDocs `json:"externalDocs,omitempty"`
// Nullable (OpenAPI 3.0)
Nullable *bool `json:"nullable,omitempty"`
// Extensions (x-* properties)
Extensions map[string]interface{} `json:"-"`
}
OpenAPISchema represents an OpenAPI 3.0 schema object
func ConvertGoTypeToOpenAPISchema ¶
func ConvertGoTypeToOpenAPISchema(goType string, fieldInfo *FieldInfo) *OpenAPISchema
ConvertGoTypeToOpenAPISchema converts a Go type string to an OpenAPI schema
func ConvertPocketBaseRecordSchema ¶
func ConvertPocketBaseRecordSchema(collection string, fields map[string]*FieldInfo) *OpenAPISchema
ConvertPocketBaseRecordSchema creates an OpenAPI schema for a PocketBase record
func ConvertStructInfoToOpenAPISchema ¶
func ConvertStructInfoToOpenAPISchema(structInfo *StructInfo) *OpenAPISchema
ConvertStructInfoToOpenAPISchema converts a StructInfo to an OpenAPI object schema
func (*OpenAPISchema) MarshalJSON ¶
func (s *OpenAPISchema) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for OpenAPISchema to handle extensions
func (*OpenAPISchema) UnmarshalJSON ¶
func (s *OpenAPISchema) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for OpenAPISchema to handle extensions
type OpenAPISchemaBuilder ¶
type OpenAPISchemaBuilder struct {
// contains filtered or unexported fields
}
OpenAPISchemaBuilder provides methods to build OpenAPI schemas from Go types
func NewOpenAPISchemaBuilder ¶
func NewOpenAPISchemaBuilder(logger Logger) *OpenAPISchemaBuilder
NewOpenAPISchemaBuilder creates a new OpenAPI schema builder
type OpenAPISecurityScheme ¶
type OpenAPISecurityScheme struct {
Type string `json:"type"`
Description string `json:"description,omitempty"`
Name string `json:"name,omitempty"`
In string `json:"in,omitempty"`
Scheme string `json:"scheme,omitempty"`
BearerFormat string `json:"bearerFormat,omitempty"`
Flows *OpenAPIOAuthFlows `json:"flows,omitempty"`
OpenIdConnectUrl string `json:"openIdConnectUrl,omitempty"`
}
OpenAPISecurityScheme represents an OpenAPI security scheme object
type OpenAPIServer ¶
type OpenAPIServer struct {
URL string `json:"url"`
Description string `json:"description,omitempty"`
Variables map[string]*OpenAPIServerVariable `json:"variables,omitempty"`
}
OpenAPIServer represents an OpenAPI server object
type OpenAPIServerVariable ¶
type OpenAPIServerVariable struct {
Enum []string `json:"enum,omitempty"`
Default string `json:"default"`
Description string `json:"description,omitempty"`
}
OpenAPIServerVariable represents an OpenAPI server variable object
type OpenAPITag ¶
type OpenAPITag struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
ExternalDocs *OpenAPIExternalDocs `json:"externalDocs,omitempty"`
}
OpenAPITag represents a tag in OpenAPI 3.0 spec
type ParamInfo ¶
type ParamInfo struct {
Name string `json:"name"`
Type string `json:"type"`
Source string `json:"source"` // "path", "query", "body", "header"
Required bool `json:"required"`
Description string `json:"description"`
Example interface{} `json:"example,omitempty"`
Validation map[string]string `json:"validation,omitempty"`
DefaultValue interface{} `json:"default_value,omitempty"`
Constraints map[string]interface{} `json:"constraints,omitempty"`
}
ParamInfo contains parameter information
type ParseError ¶
type ParseError struct {
Type string `json:"type"`
Message string `json:"message"`
File string `json:"file,omitempty"`
Line int `json:"line,omitempty"`
Column int `json:"column,omitempty"`
Context string `json:"context,omitempty"`
}
ParseError represents a parsing error with context
func (ParseError) Error ¶
func (e ParseError) Error() string
type PathAnalyzer ¶
type PathAnalyzer struct{}
PathAnalyzer provides utilities for analyzing URL paths
func NewPathAnalyzer ¶
func NewPathAnalyzer() *PathAnalyzer
NewPathAnalyzer creates a new path analyzer
func (*PathAnalyzer) ExtractParameters ¶
func (pa *PathAnalyzer) ExtractParameters(path string) []string
ExtractParameters extracts parameter information from a path
func (*PathAnalyzer) ExtractTags ¶
func (pa *PathAnalyzer) ExtractTags(path string) []string
ExtractTags extracts meaningful tags from a URL path
func (*PathAnalyzer) GenerateDescription ¶
func (pa *PathAnalyzer) GenerateDescription(method, path string) string
GenerateDescription generates a description based on the path structure
type PocketBasePatterns ¶
type PocketBasePatterns struct {
RequestPatterns map[string]RequestPattern `json:"request_patterns"`
ResponsePatterns map[string]ResponsePattern `json:"response_patterns"`
AuthPatterns []AuthPattern `json:"auth_patterns"`
}
PocketBasePatterns contains PocketBase-specific parsing patterns
func NewPocketBasePatterns ¶
func NewPocketBasePatterns() *PocketBasePatterns
NewPocketBasePatterns creates PocketBase-specific patterns
type PrefixedRouter ¶
type PrefixedRouter struct {
// contains filtered or unexported fields
}
PrefixedRouter wraps a VersionedAPIRouter with automatic path prefixing
func (*PrefixedRouter) CRUD ¶
func (pr *PrefixedRouter) CRUD(resource string, handlers CRUDHandlers, authMiddleware ...interface{})
CRUD registers standard CRUD routes for a resource
func (*PrefixedRouter) DELETE ¶
func (pr *PrefixedRouter) DELETE(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
DELETE registers a DELETE route with automatic prefix
func (*PrefixedRouter) GET ¶
func (pr *PrefixedRouter) GET(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
GET registers a GET route with automatic prefix
func (*PrefixedRouter) PATCH ¶
func (pr *PrefixedRouter) PATCH(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
PATCH registers a PATCH route with automatic prefix
func (*PrefixedRouter) POST ¶
func (pr *PrefixedRouter) POST(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
POST registers a POST route with automatic prefix
func (*PrefixedRouter) PUT ¶
func (pr *PrefixedRouter) PUT(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
PUT registers a PUT route with automatic prefix
type RegistryHelper ¶
type RegistryHelper struct {
// contains filtered or unexported fields
}
RegistryHelper provides utilities to help the registry build documentation
func NewRegistryHelper ¶
func NewRegistryHelper() *RegistryHelper
NewRegistryHelper creates a new registry helper
func (*RegistryHelper) AnalyzeRoute ¶
func (rh *RegistryHelper) AnalyzeRoute(method, path string, handler func(*core.RequestEvent) error, middlewares []interface{}) *RouteAnalysis
AnalyzeRoute provides comprehensive analysis of a route
type RequestPattern ¶
type RequestPattern struct {
Method string `json:"method"`
StructType string `json:"struct_type"`
Description string `json:"description"`
}
RequestPattern defines a PocketBase request pattern
type RequestResponseAnalyzer ¶
type RequestResponseAnalyzer struct {
// contains filtered or unexported fields
}
RequestResponseAnalyzer analyzes handler functions to extract request/response types
type ResponsePattern ¶
type ResponsePattern struct {
Method string `json:"method"`
ReturnType string `json:"return_type"`
Description string `json:"description"`
}
ResponsePattern defines a PocketBase response pattern
type RouteAnalysis ¶
type RouteAnalysis struct {
Method string `json:"method"`
Path string `json:"path"`
Handler *HandlerInfo `json:"handler"`
Auth *AuthInfo `json:"auth,omitempty"`
Description string `json:"description"`
Tags []string `json:"tags"`
Parameters []string `json:"parameters"`
}
RouteAnalysis contains the result of route analysis
type RouteAnalyzer ¶
type RouteAnalyzer struct{}
RouteAnalyzer provides utilities for analyzing routes and handlers
Example ¶
// Create a new route analyzer
analyzer := NewRouteAnalyzer()
// Define a handler function
handler := func(c *core.RequestEvent) error {
// Handle the request
return nil
}
// Analyze the handler
info := analyzer.AnalyzeHandler(handler)
println("Handler Name:", info.Name)
println("Package:", info.Package)
println("Description:", info.Description)
func NewRouteAnalyzer ¶
func NewRouteAnalyzer() *RouteAnalyzer
NewRouteAnalyzer creates a new route analyzer
func (*RouteAnalyzer) AnalyzeHandler ¶
func (ra *RouteAnalyzer) AnalyzeHandler(handler func(*core.RequestEvent) error) *HandlerInfo
AnalyzeHandler analyzes a handler function and returns information about it
Example ¶
analyzer := NewRouteAnalyzer()
// Analyze a specific handler
info := analyzer.AnalyzeHandler(discoveryTestHandler)
println("Analyzed handler:")
println(" Name:", info.Name)
println(" Full Name:", info.FullName)
println(" Package:", info.Package)
println(" Description:", info.Description)
// This information can be used for automatic API documentation
if info.Name != "" {
println("This handler can be documented automatically")
}
type RouteDefinition ¶
type RouteDefinition struct {
Method string
Path string
Handler func(*core.RequestEvent) error
Middlewares []interface{}
}
RouteDefinition represents an explicit route definition
type RouteRegistrar ¶
type RouteRegistrar func(vm *APIVersionManager) error
type SchemaAnalysisResult ¶
type SchemaAnalysisResult struct {
RequestSchema *OpenAPISchema `json:"request_schema,omitempty"`
ResponseSchema *OpenAPISchema `json:"response_schema,omitempty"`
Parameters []*OpenAPIParameter `json:"parameters,omitempty"`
Errors []error `json:"errors,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
SchemaAnalysisResult contains the result of schema analysis
type SchemaConfig ¶
type SchemaConfig struct {
SystemFields []string `json:"system_fields"`
DefaultParameterType string `json:"default_parameter_type"`
DefaultParameterIn string `json:"default_parameter_in"`
DefaultContentType string `json:"default_content_type"`
DescriptionTemplates map[string]string `json:"description_templates"`
SupportedContentTypes []string `json:"supported_content_types"`
}
SchemaConfig holds configuration for schema processing
func DefaultSchemaConfig ¶
func DefaultSchemaConfig() *SchemaConfig
DefaultSchemaConfig returns a default schema configuration
type SchemaConversionResult ¶
type SchemaConversionResult struct {
Schema *OpenAPISchema `json:"schema"`
Components map[string]*OpenAPISchema `json:"components,omitempty"`
Errors []error `json:"errors,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
SchemaConversionResult contains the result of schema conversion
type SchemaGenerator ¶
type SchemaGenerator struct {
// contains filtered or unexported fields
}
SchemaGenerator handles all schema generation and analysis operations
Example ¶
// Create AST parser and schema generator
astParser := NewMockASTParserForSchema()
schemaGen := NewSchemaGenerator(astParser)
// Add mock struct data
userStruct := createTestStructInfo("User")
astParser.AddMockStruct("User", userStruct)
// Create an endpoint
endpoint := &APIEndpoint{
Method: "GET",
Path: "/users/{id}",
Handler: "getUserHandler",
Description: "Get user by ID",
Tags: []string{"users"},
}
// Analyze schemas
requestSchema, _ := schemaGen.AnalyzeRequestSchema(endpoint)
responseSchema, _ := schemaGen.AnalyzeResponseSchema(endpoint)
// Generate full endpoint schema
endpointSchema, _ := schemaGen.GetOpenAPIEndpointSchema(endpoint)
println("Request schema:", requestSchema != nil)
println("Response schema:", responseSchema != nil)
println("Full endpoint schema:", endpointSchema != nil)
func NewSchemaGenerator ¶
func NewSchemaGenerator(astParser ASTParserInterface) *SchemaGenerator
NewSchemaGenerator creates a new schema generator with the given AST parser
func (*SchemaGenerator) AnalyzeRequestSchema ¶
func (sg *SchemaGenerator) AnalyzeRequestSchema(endpoint *APIEndpoint) (*OpenAPISchema, error)
AnalyzeRequestSchema analyzes and generates request schema for an endpoint
func (*SchemaGenerator) AnalyzeResponseSchema ¶
func (sg *SchemaGenerator) AnalyzeResponseSchema(endpoint *APIEndpoint) (*OpenAPISchema, error)
AnalyzeResponseSchema analyzes and generates response schema for an endpoint
func (*SchemaGenerator) AnalyzeSchemaFromPath ¶
func (sg *SchemaGenerator) AnalyzeSchemaFromPath(method, path string) (*SchemaAnalysisResult, error)
AnalyzeSchemaFromPath analyzes schemas for a given method and path
func (*SchemaGenerator) GenerateComponentSchemas ¶
func (sg *SchemaGenerator) GenerateComponentSchemas() *OpenAPIComponents
GenerateComponentSchemas generates OpenAPI component schemas from AST data
Example ¶
astParser := NewMockASTParserForSchema()
schemaGen := NewSchemaGenerator(astParser)
// Add mock structs
userStruct := createTestStructInfo("User")
astParser.AddMockStruct("User", userStruct)
// Generate component schemas
components := schemaGen.GenerateComponentSchemas()
println("Generated components with", len(components.Schemas), "schemas")
println("Generated", len(components.Responses), "response components")
println("Generated", len(components.Parameters), "parameter components")
func (*SchemaGenerator) GetOpenAPIEndpointSchema ¶
func (sg *SchemaGenerator) GetOpenAPIEndpointSchema(endpoint *APIEndpoint) (*OpenAPIEndpointSchema, error)
GetOpenAPIEndpointSchema generates a complete OpenAPI endpoint schema
type SchemaGeneratorInterface ¶
type SchemaGeneratorInterface interface {
AnalyzeRequestSchema(endpoint *APIEndpoint) (*OpenAPISchema, error)
AnalyzeResponseSchema(endpoint *APIEndpoint) (*OpenAPISchema, error)
AnalyzeSchemaFromPath(method, path string) (*SchemaAnalysisResult, error)
GenerateComponentSchemas() *OpenAPIComponents
GetOpenAPIEndpointSchema(endpoint *APIEndpoint) (*OpenAPIEndpointSchema, error)
}
SchemaGeneratorInterface defines the contract for schema generation operations
type SchemaPattern ¶
type SchemaPattern struct {
Name string `json:"name"`
HandlerMatch func(string) bool `json:"-"`
PathMatch func(string) bool `json:"-"`
RequestGen func() *OpenAPISchema `json:"-"`
ResponseGen func() *OpenAPISchema `json:"-"`
}
SchemaPattern represents a pattern for matching handlers/paths to generate schemas
type SourceLocation ¶
type SourceLocation struct {
File string `json:"file"`
Line int `json:"line"`
Column int `json:"column"`
}
SourceLocation contains source code location information
type SpecGenerator ¶
type SpecGenerator struct {
// contains filtered or unexported fields
}
func NewSpecGenerator ¶
func NewSpecGenerator(configs VersionConfigProvider, routes RouteRegistrar) *SpecGenerator
func NewSpecGeneratorWithInitializer ¶
func NewSpecGeneratorWithInitializer(initializer VersionManagerInitializer) *SpecGenerator
func (*SpecGenerator) Generate ¶
func (sg *SpecGenerator) Generate(outputDir string, onlyVersion string) error
func (*SpecGenerator) Validate ¶
func (sg *SpecGenerator) Validate(specsDir string) error
type StructInfo ¶
type StructInfo struct {
Name string `json:"name"`
Package string `json:"package"`
Fields map[string]*FieldInfo `json:"fields"`
JSONSchema *OpenAPISchema `json:"json_schema"`
Description string `json:"description"`
Tags []string `json:"tags"`
Embedded []string `json:"embedded,omitempty"`
Methods []string `json:"methods,omitempty"`
Implements []string `json:"implements,omitempty"`
IsGeneric bool `json:"is_generic"`
TypeParams []string `json:"type_params,omitempty"`
Documentation *Documentation `json:"documentation,omitempty"`
SourceLocation *SourceLocation `json:"source_location,omitempty"`
}
StructInfo contains comprehensive struct information
type TypeInfo ¶
type TypeInfo struct {
Name string `json:"name"`
Kind string `json:"kind"` // "struct", "slice", "map", "interface", etc.
ElementType *TypeInfo `json:"element_type,omitempty"`
KeyType *TypeInfo `json:"key_type,omitempty"`
ValueType *TypeInfo `json:"value_type,omitempty"`
Fields map[string]*FieldInfo `json:"fields,omitempty"`
Schema *OpenAPISchema `json:"schema,omitempty"`
IsPointer bool `json:"is_pointer"`
IsGeneric bool `json:"is_generic"`
TypeParams []string `json:"type_params,omitempty"`
Package string `json:"package"`
Constraints map[string]interface{} `json:"constraints,omitempty"`
}
TypeInfo contains type information for complex types
type TypeSchemaBuilder ¶
type TypeSchemaBuilder struct {
// contains filtered or unexported fields
}
TypeSchemaBuilder converts Go types to OpenAPI schema representations
type TypeValidator ¶
TypeValidator interface for type validation
type ValidationExtractor ¶
type ValidationExtractor struct {
// contains filtered or unexported fields
}
ValidationExtractor extracts validation rules from struct tags and comments
type VersionConfigProvider ¶
type VersionConfigProvider func() map[string]*APIDocsConfig
type VersionInfo ¶
type VersionInfo struct {
Version string `json:"version"`
Status string `json:"status"` // "stable", "development", "deprecated"
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Config *APIDocsConfig `json:"config"`
Stats map[string]int `json:"stats"`
Endpoints int `json:"endpoints"`
}
VersionInfo contains information about a specific API version
type VersionManagerInitializer ¶
type VersionManagerInitializer func() (*APIVersionManager, error)
type VersionSetup ¶
type VersionSetup struct {
Config *APIDocsConfig
Routes func(*VersionedAPIRouter)
}
VersionSetup combines version configuration and route registration for streamlined setup
type VersionedAPIRouter ¶
type VersionedAPIRouter struct {
// contains filtered or unexported fields
}
VersionedAPIRouter provides version-specific route registration
Example ¶
vm := NewAPIVersionManager()
config := &APIDocsConfig{Title: "API v1", Version: "1.0.0", Enabled: true}
vm.RegisterVersion("v1", config)
// Skip actual router usage since we can't properly mock ServeEvent
fmt.Printf("Version manager created with version: %s\n", vm.GetDefaultVersion())
Output: Version manager created with version: v1
func (*VersionedAPIRouter) DELETE ¶
func (vr *VersionedAPIRouter) DELETE(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
DELETE registers a DELETE route with automatic documentation
func (*VersionedAPIRouter) GET ¶
func (vr *VersionedAPIRouter) GET(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
GET registers a GET route with automatic documentation
func (*VersionedAPIRouter) GetRegistry ¶
func (vr *VersionedAPIRouter) GetRegistry() *APIRegistry
GetRegistry returns the version-specific registry
func (*VersionedAPIRouter) GetVersion ¶
func (vr *VersionedAPIRouter) GetVersion() string
GetVersion returns the version of this router
func (*VersionedAPIRouter) GetVersionManager ¶
func (vr *VersionedAPIRouter) GetVersionManager() *APIVersionManager
GetVersionManager returns the version manager
func (*VersionedAPIRouter) PATCH ¶
func (vr *VersionedAPIRouter) PATCH(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
PATCH registers a PATCH route with automatic documentation
func (*VersionedAPIRouter) POST ¶
func (vr *VersionedAPIRouter) POST(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
POST registers a POST route with automatic documentation
func (*VersionedAPIRouter) PUT ¶
func (vr *VersionedAPIRouter) PUT(path string, handler func(*core.RequestEvent) error) *VersionedRouteChain
PUT registers a PUT route with automatic documentation
func (*VersionedAPIRouter) SetPrefix ¶
func (vr *VersionedAPIRouter) SetPrefix(prefix string) *PrefixedRouter
SetPrefix sets a default prefix for this router to avoid repetition
type VersionedRouteChain ¶
type VersionedRouteChain struct {
// contains filtered or unexported fields
}
VersionedRouteChain represents a chainable route for middleware binding
func (*VersionedRouteChain) Bind ¶
func (vrc *VersionedRouteChain) Bind(middlewares ...interface{}) *VersionedRouteChain
Bind detects middleware binding and re-registers route with middleware documentation AND binds middleware to the actual PocketBase route so it executes at runtime. Accepts *hook.Handler[*core.RequestEvent] and plain func(*core.RequestEvent) error values. Plain funcs are wrapped in an anonymous hook.Handler before forwarding to PocketBase.
func (*VersionedRouteChain) BindFunc ¶
func (vrc *VersionedRouteChain) BindFunc(middlewareFuncs ...func(*core.RequestEvent) error) *VersionedRouteChain
BindFunc registers plain middleware functions to the route. This mirrors PocketBase's Route.BindFunc API and is the ergonomic counterpart to Bind(). Each func is forwarded to the underlying PocketBase route via BindFunc, and also stored (wrapped) for docs registry analysis.