Documentation
¶
Overview ¶
Package openapi defines helpers for OpenAPI schema generation from Go types.
Package annot8 provides enum detection and schema generation for string-based Go enums.
Package annot8 provides JSON-schema tag parsing utilities.
Test file to check enum extraction edge cases
Index ¶
- Constants
- func AddExternalKnownType(name string, schema *Schema)
- func AddResponseHeader(response *Response, name string, header Header)
- func AddResponseLink(response *Response, name string, link Link)
- func AddSchemaEnum(schema *Schema, values ...interface{})
- func AddSchemaExample(schema *Schema, example interface{})
- func DefaultModelNameFunc(pkg, name string) string
- func GenerateOpenAPISpecFile(p *GenerateParams) error
- func MarkSchemaDeprecated(schema *Schema)
- func MarkSchemaReadOnly(schema *Schema)
- func MarkSchemaWriteOnly(schema *Schema)
- func SetSchemaArrayConstraints(schema *Schema, minItems, maxItems *int, uniqueItems *bool)
- func SetSchemaFormat(schema *Schema, format string)
- func SetSchemaPattern(schema *Schema, pattern string)
- func SetSchemaRange(schema *Schema, min, max *float64)
- func SetSchemaStringLength(schema *Schema, minLen, maxLen *int)
- func SwaggerUIHandler(specURL string) http.HandlerFunc
- type Annotation
- type AnnotationParsingError
- type Callback
- type Components
- type Config
- type Contact
- type Discriminator
- type Encoding
- type ErrorResponse
- type Example
- type ExternalDocumentation
- type GenerateParams
- type Generator
- type HandlerInfo
- type Header
- type Info
- type License
- type Link
- type MediaTypeObject
- type ModelNameFunc
- type Operation
- type ParamAnnotation
- type Parameter
- type PathItem
- type RequestBody
- type Response
- type RouteDiscoveryError
- type RouteInfo
- type Schema
- type SchemaGenerator
- type SecurityRequirement
- type SecurityScheme
- type Server
- type Spec
- type StatusEnum
- type SuccessResponse
- type Tag
- type TypeA
- type TypeB
- type TypeIndex
- func (idx *TypeIndex) GetQualifiedTypeName(typeName string) string
- func (idx *TypeIndex) LookupFile(filePath string) *ast.File
- func (idx *TypeIndex) LookupQualifiedType(qualifiedName string) *ast.TypeSpec
- func (idx *TypeIndex) LookupType(pkg, typeName string) *ast.TypeSpec
- func (idx *TypeIndex) LookupUnqualifiedType(typeName string) (*ast.TypeSpec, string)
- type Webhooks
- type XML
Constants ¶
const ( TypeAVal1 TypeA = "a1" TypeAVal2 TypeA = "a2" TypeBVal1 TypeB = "b1" TypeBVal2 TypeB = "b2" )
Variables ¶
This section is empty.
Functions ¶
func AddExternalKnownType ¶
func AddResponseHeader ¶
AddResponseHeader appends a header to a response definition.
func AddResponseLink ¶
AddResponseLink appends a link to a response definition.
func AddSchemaEnum ¶
func AddSchemaEnum(schema *Schema, values ...interface{})
AddSchemaEnum appends values to the enum list.
func AddSchemaExample ¶
func AddSchemaExample(schema *Schema, example interface{})
AddSchemaExample registers a named example on the schema.
func DefaultModelNameFunc ¶
DefaultModelNameFunc returns names in "pkg.Type" format (existing default).
func GenerateOpenAPISpecFile ¶
func GenerateOpenAPISpecFile(p *GenerateParams) error
GenerateOpenAPISpecFile generates the OpenAPI spec and writes it to the given file path.
func MarkSchemaDeprecated ¶
func MarkSchemaDeprecated(schema *Schema)
MarkSchemaDeprecated marks a schema as deprecated.
func MarkSchemaReadOnly ¶
func MarkSchemaReadOnly(schema *Schema)
MarkSchemaReadOnly marks a schema as read-only.
func MarkSchemaWriteOnly ¶
func MarkSchemaWriteOnly(schema *Schema)
MarkSchemaWriteOnly marks a schema as write-only.
func SetSchemaArrayConstraints ¶
SetSchemaArrayConstraints sets array constraints.
func SetSchemaFormat ¶
SetSchemaFormat sets the schema format.
func SetSchemaPattern ¶
SetSchemaPattern sets the schema pattern.
func SetSchemaRange ¶
SetSchemaRange sets inclusive numeric range constraints.
func SetSchemaStringLength ¶
SetSchemaStringLength sets string length constraints.
func SwaggerUIHandler ¶
func SwaggerUIHandler(specURL string) http.HandlerFunc
Types ¶
type Annotation ¶
type Annotation struct {
Summary string
Description string
Tags []string
Accept []string
Produce []string
Security []string
Parameters []ParamAnnotation
Success *SuccessResponse
Failures []ErrorResponse
}
Annotation represents parsed swagger annotations
func ParseAnnotations ¶
func ParseAnnotations(filePath, functionName string) (*Annotation, error)
type AnnotationParsingError ¶
type AnnotationParsingError struct {
Messages []string
}
AnnotationParsingError represents errors encountered while parsing annotation lines. It contains one or more error messages for malformed annotation directives.
func (*AnnotationParsingError) Error ¶
func (e *AnnotationParsingError) Error() string
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"`
Examples map[string]Example `json:"examples,omitempty"`
RequestBodies map[string]RequestBody `json:"requestBodies,omitempty"`
Headers map[string]Header `json:"headers,omitempty"`
SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty"`
Links map[string]Link `json:"links,omitempty"`
Callbacks map[string]Callback `json:"callbacks,omitempty"`
PathItems map[string]PathItem `json:"pathItems,omitempty"`
}
Components stores re-usable OpenAPI components.
type Config ¶
type Config struct {
Title string // Required: API title
Summary string // Optional: API summary
Description string // Optional: API description
Version string // Required: API version (e.g., "1.0.0")
TermsOfService string // Optional: Terms of service URL
Servers []string // Optional: List of base server URLs
Contact *Contact // Optional: Contact information
License *License // Optional: License information
}
Config defines the configuration for OpenAPI specification generation. All fields except Title and Version are optional.
type Contact ¶
type Contact struct {
Name string // Contact name
URL string // Contact URL
Email string // Contact email address
}
Contact represents contact information for the API.
type Discriminator ¶
type Discriminator struct {
PropertyName string `json:"propertyName"`
Mapping map[string]string `json:"mapping,omitempty"`
}
Discriminator represents OpenAPI 3.1 discriminators for polymorphic schemas.
type Encoding ¶
type Encoding struct {
ContentType string `json:"contentType,omitempty"`
Headers map[string]*Header `json:"headers,omitempty"`
Style string `json:"style,omitempty"`
Explode *bool `json:"explode,omitempty"`
AllowReserved bool `json:"allowReserved,omitempty"`
}
Encoding represents OpenAPI 3.1 encoding for request/response content.
type ErrorResponse ¶
type Example ¶
type Example struct {
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Value any `json:"value,omitempty"`
ExternalValue string `json:"externalValue,omitempty"`
}
Example represents a concrete example payload.
type ExternalDocumentation ¶
type ExternalDocumentation struct {
Description string `json:"description,omitempty"`
URL string `json:"url"`
}
ExternalDocumentation represents OpenAPI 3.1 external documentation.
type GenerateParams ¶
type GenerateParams struct {
Router chi.Router
Config Config
FilePath string
RenameFunction ModelNameFunc
}
type Generator ¶
type Generator struct {
// contains filtered or unexported fields
}
Generator produces OpenAPI specifications by analysing Chi routers.
func NewGenerator ¶
func NewGenerator() *Generator
NewGenerator creates a generator using the shared global TypeIndex.
func NewGeneratorWithCache ¶
NewGeneratorWithCache creates a generator that reuses a pre-built TypeIndex.
func (*Generator) AddWebhook ¶
AddWebhook attaches a webhook path item to the specification.
func (*Generator) GenerateSchema ¶
GenerateSchema manually adds a type to the internal schema generator. This is useful for including types that are not automatically discovered via routes.
func (*Generator) GenerateSpec ¶
GenerateSpec assembles an OpenAPI specification for the supplied router.
func (*Generator) SetModelNameFunc ¶
func (g *Generator) SetModelNameFunc(f ModelNameFunc)
SetModelNameFunc sets a custom strategy for naming OpenAPI models.
type HandlerInfo ¶
HandlerInfo describes the source location for a handler function.
type Header ¶
type Header struct {
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
Deprecated bool `json:"deprecated,omitempty"`
AllowEmptyValue bool `json:"allowEmptyValue,omitempty"`
Schema *Schema `json:"schema,omitempty"`
Example any `json:"example,omitempty"`
Examples map[string]*Example `json:"examples,omitempty"`
}
Header represents OpenAPI 3.1 header metadata.
type Info ¶
type Info struct {
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
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 captures high-level metadata about the API.
type License ¶
type License struct {
Name string `json:"name"` // License name (e.g., "MIT", "Apache 2.0")
Identifier string `json:"identifier,omitempty"`
URL string `json:"url,omitempty"` // License URL
}
License represents license information for the API.
type Link ¶
type Link struct {
OperationRef string `json:"operationRef,omitempty"`
OperationId string `json:"operationId,omitempty"`
Parameters map[string]any `json:"parameters,omitempty"`
RequestBody any `json:"requestBody,omitempty"`
Description string `json:"description,omitempty"`
Server *Server `json:"server,omitempty"`
}
Link represents OpenAPI 3.1 link objects.
type MediaTypeObject ¶
type MediaTypeObject struct {
Schema *Schema `json:"schema,omitempty"`
Example any `json:"example,omitempty"`
Examples map[string]Example `json:"examples,omitempty"`
Encoding map[string]Encoding `json:"encoding,omitempty"`
}
MediaTypeObject wraps schema and examples for a specific media type.
type ModelNameFunc ¶
ModelNameFunc defines a strategy for converting Go package and type names into OpenAPI model names.
type Operation ¶
type Operation struct {
Tags []string `json:"tags,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
OperationID string `json:"operationId,omitempty"`
Parameters []Parameter `json:"parameters,omitempty"`
RequestBody *RequestBody `json:"requestBody,omitempty"`
Responses map[string]Response `json:"responses"`
Callbacks map[string]Callback `json:"callbacks,omitempty"`
Deprecated bool `json:"deprecated,omitempty"`
Security []SecurityRequirement `json:"security,omitempty"`
Servers []Server `json:"servers,omitempty"`
}
Operation represents a single HTTP operation.
type ParamAnnotation ¶
type Parameter ¶
type Parameter struct {
Name string `json:"name"`
In string `json:"in"`
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
Schema *Schema `json:"schema,omitempty"`
}
Parameter describes a path/query/header parameter.
type PathItem ¶
type PathItem struct {
Ref string `json:"$ref,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Get *Operation `json:"get,omitempty"`
Put *Operation `json:"put,omitempty"`
Post *Operation `json:"post,omitempty"`
Delete *Operation `json:"delete,omitempty"`
Options *Operation `json:"options,omitempty"`
Head *Operation `json:"head,omitempty"`
Patch *Operation `json:"patch,omitempty"`
Trace *Operation `json:"trace,omitempty"`
Servers []Server `json:"servers,omitempty"`
Parameters []Parameter `json:"parameters,omitempty"`
}
PathItem groups operations under a single route.
type RequestBody ¶
type RequestBody struct {
Description string `json:"description,omitempty"`
Content map[string]MediaTypeObject `json:"content"`
Required bool `json:"required,omitempty"`
}
RequestBody describes an HTTP request payload.
type Response ¶
type Response struct {
Description string `json:"description"`
Headers map[string]Header `json:"headers,omitempty"`
Content map[string]MediaTypeObject `json:"content,omitempty"`
Links map[string]Link `json:"links,omitempty"`
}
Response captures the structure of an HTTP response.
type RouteDiscoveryError ¶
RouteDiscoveryError represents an error that occurred during route discovery.
func (*RouteDiscoveryError) Error ¶
func (e *RouteDiscoveryError) Error() string
func (*RouteDiscoveryError) Unwrap ¶
func (e *RouteDiscoveryError) Unwrap() error
type RouteInfo ¶
type RouteInfo struct {
Method string
Pattern string
HandlerName string
HandlerFunc http.HandlerFunc
Middlewares []func(http.Handler) http.Handler
}
RouteInfo holds metadata about each registered route including HTTP method, path pattern, handler name, and function.
func DiscoverRoutes ¶
DiscoverRoutes returns only non-internal routes for OpenAPI spec assembly. This function filters out routes that are part of the OpenAPI tooling itself (such as /swagger and /annot8 endpoints) to avoid circular references in the specification.
type Schema ¶
type Schema struct {
Type any `json:"type,omitempty"`
Properties map[string]*Schema `json:"properties,omitempty"`
Items *Schema `json:"items,omitempty"`
Required []string `json:"required,omitempty"`
AdditionalProperties any `json:"additionalProperties,omitempty"`
Ref string `json:"$ref,omitempty"`
Description string `json:"description,omitempty"`
Format string `json:"format,omitempty"`
Pattern string `json:"pattern,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
ExclusiveMinimum *float64 `json:"exclusiveMinimum,omitempty"`
ExclusiveMaximum *float64 `json:"exclusiveMaximum,omitempty"`
MinLength *int `json:"minLength,omitempty"`
MaxLength *int `json:"maxLength,omitempty"`
MinItems *int `json:"minItems,omitempty"`
MaxItems *int `json:"maxItems,omitempty"`
UniqueItems *bool `json:"uniqueItems,omitempty"`
Enum []any `json:"enum,omitempty"`
Const any `json:"const,omitempty"`
Default any `json:"default,omitempty"`
Example any `json:"example,omitempty"`
Examples []any `json:"examples,omitempty"`
OneOf []*Schema `json:"oneOf,omitempty"`
AnyOf []*Schema `json:"anyOf,omitempty"`
AllOf []*Schema `json:"allOf,omitempty"`
Not *Schema `json:"not,omitempty"`
Title string `json:"title,omitempty"`
Deprecated *bool `json:"deprecated,omitempty"`
ReadOnly *bool `json:"readOnly,omitempty"`
WriteOnly *bool `json:"writeOnly,omitempty"`
XML *XML `json:"xml,omitempty"`
ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
Discriminator *Discriminator `json:"discriminator,omitempty"`
}
Schema represents an OpenAPI schema definition.
func CreateAllOfSchema ¶
CreateAllOfSchema returns a schema composed with allOf.
func CreateAnyOfSchema ¶
CreateAnyOfSchema returns a schema composed with anyOf.
func CreateOneOfSchema ¶
CreateOneOfSchema returns a schema composed with oneOf.
type SchemaGenerator ¶
type SchemaGenerator struct {
// contains filtered or unexported fields
}
SchemaGenerator handles dynamic schema generation from Go types If a TypeIndex is provided, it will be used for fast lookup.
func NewSchemaGenerator ¶
func NewSchemaGenerator(opts ...*TypeIndex) *SchemaGenerator
NewSchemaGenerator creates a new schema generator. Optionally accepts a TypeIndex.
func (*SchemaGenerator) GenerateSchema ¶
func (sg *SchemaGenerator) GenerateSchema(typeName string) *Schema
GenerateSchema creates a JSON schema for the given type name. All types are stored using qualified names (e.g., "order.CreateReq", "sqlc.User").
func (*SchemaGenerator) GetSchemas ¶
func (sg *SchemaGenerator) GetSchemas() map[string]Schema
GetSchemas returns all generated schemas.
type SecurityRequirement ¶
SecurityRequirement represents a security requirement.
type SecurityScheme ¶
type SecurityScheme struct {
Type string `json:"type"`
Scheme string `json:"scheme,omitempty"`
BearerFormat string `json:"bearerFormat,omitempty"`
Description string `json:"description,omitempty"`
}
SecurityScheme represents a security scheme configuration.
type Spec ¶
type Spec struct {
OpenAPI string `json:"openapi"`
Info Info `json:"info"`
JSONSchemaDialect string `json:"jsonSchemaDialect,omitempty"`
Servers []Server `json:"servers,omitempty"`
Paths map[string]PathItem `json:"paths"`
Webhooks Webhooks `json:"webhooks,omitempty"`
Components *Components `json:"components,omitempty"`
Tags []Tag `json:"tags,omitempty"`
Security []SecurityRequirement `json:"security,omitempty"`
ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
}
Spec represents a complete OpenAPI 3.1 specification.
type StatusEnum ¶
type StatusEnum string
EnumWithImplicitType tests const with implicit type from predecessor
const ( StatusActive StatusEnum = "active" StatusInactive = "inactive" // Implicitly StatusEnum StatusPending StatusEnum = "pending" )
type SuccessResponse ¶
type TypeIndex ¶
type TypeIndex struct {
// contains filtered or unexported fields
}
TypeIndex provides fast lookup of type definitions by package and type name.
func BuildTypeIndex ¶
func BuildTypeIndex() *TypeIndex
BuildTypeIndex scans the given roots and builds a type index for all Go types.
func GetTypeIndex ¶
func GetTypeIndex() *TypeIndex
func (*TypeIndex) GetQualifiedTypeName ¶
GetQualifiedTypeName returns the appropriate qualified name for a type
func (*TypeIndex) LookupFile ¶
LookupFile returns the AST for a given file path, handling normalization and case-insensitivity on Windows.
func (*TypeIndex) LookupQualifiedType ¶
LookupQualifiedType returns the TypeSpec for a qualified type name (e.g., "order.CreateReq")
func (*TypeIndex) LookupType ¶
LookupType returns the TypeSpec for a given package and type name, or nil if not found.
