Documentation
¶
Overview ¶
Package openapi defines helpers for OpenAPI schema generation from Go types.
Package openapi provides enum detection and schema generation for string-based Go enums.
Package openapi provides enum test examples for schema generation.
Package openapi provides struct-to-schema conversion logic.
Package openapi provides JSON-schema tag parsing utilities.
Index ¶
- 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, name string, example Example)
- func AssertDeepEqual(t *testing.T, expected, actual interface{})
- func AssertEqual[T comparable](t *testing.T, expected, actual T)
- func AssertJSONEqual(t *testing.T, want, got []byte)
- func AssertNoError(t *testing.T, err error)
- func CachedHandler(router chi.Router, cfg Config) http.HandlerFunc
- func GenerateFileHandler(router chi.Router, cfg Config) http.HandlerFunc
- func GenerateOpenAPISpecFile(router chi.Router, cfg Config, filePath string, refresh bool) error
- func InvalidateCache(w http.ResponseWriter, _ *http.Request)
- func MarkSchemaDeprecated(schema *Schema)
- func MarkSchemaReadOnly(schema *Schema)
- func MarkSchemaWriteOnly(schema *Schema)
- func Request(handler http.Handler, method, path string, body io.Reader) *httptest.ResponseRecorder
- func ResetGlobals()
- 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)
- type Annotation
- type AnnotationParsingError
- type Callback
- type Components
- type Config
- type Contact
- type Discriminator
- type Encoding
- type ErrorResponse
- type Example
- type ExternalDocumentation
- type Generator
- type HandlerInfo
- type Header
- type Info
- type License
- type Link
- type MediaTypeObject
- type MyEnum
- 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 SuccessResponse
- type Tag
- type TypeIndex
- type Webhooks
- type XML
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddExternalKnownType ¶
func AddResponseHeader ¶
AddResponseHeader adds a header to a response
func AddResponseLink ¶
AddResponseLink adds a link to a response
func AddSchemaEnum ¶
func AddSchemaEnum(schema *Schema, values ...interface{})
AddSchemaEnum adds enum values to a schema
func AddSchemaExample ¶
AddSchemaExample adds an example to a schema
func AssertDeepEqual ¶ added in v0.3.0
AssertDeepEqual fails the test if expected and actual are not deeply equal.
func AssertEqual ¶ added in v0.3.0
func AssertEqual[T comparable](t *testing.T, expected, actual T)
AssertEqual fails the test if expected != actual.
func AssertJSONEqual ¶ added in v0.3.0
AssertJSONEqual fails if two JSON byte slices are not equivalent.
func AssertNoError ¶ added in v0.3.0
AssertNoError fails the test if err is non-nil.
func CachedHandler ¶
func CachedHandler(router chi.Router, cfg Config) http.HandlerFunc
CachedHandler returns an HTTP handler that serves the OpenAPI specification. The specification is cached and only regenerated when refresh=true is passed as a query parameter or when the cache is invalidated.
func GenerateFileHandler ¶
func GenerateFileHandler(router chi.Router, cfg Config) http.HandlerFunc
GenerateFileHandler is an HTTP handler that generates the OpenAPI spec file and returns a status message.
func GenerateOpenAPISpecFile ¶
GenerateOpenAPISpecFile generates the OpenAPI spec and writes it to the given file path.
func InvalidateCache ¶
func InvalidateCache(w http.ResponseWriter, _ *http.Request)
InvalidateCache invalidates the cached OpenAPI specification. The next request will trigger regeneration of the specification.
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 Request ¶ added in v0.3.0
Request creates an HTTP request against handler and returns a recorder.
func ResetGlobals ¶ added in v0.3.0
func ResetGlobals()
ResetGlobals resets any global state for testing.
func SetSchemaArrayConstraints ¶
SetSchemaArrayConstraints sets array constraints
func SetSchemaFormat ¶
SetSchemaFormat sets the format for a schema (e.g., "date-time", "email", "uuid")
func SetSchemaPattern ¶
SetSchemaPattern sets a regex pattern for string validation
func SetSchemaRange ¶
SetSchemaRange sets minimum and maximum values for numeric types
func SetSchemaStringLength ¶
SetSchemaStringLength sets minimum and maximum length for strings
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)
ParseAnnotations extracts OpenAPI annotations from Go source comments for a given function. It returns an Annotation struct and an error if any annotation lines were malformed.
type AnnotationParsingError ¶ added in v0.2.0
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 ¶ added in v0.2.0
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"` // OpenAPI 3.1 feature }
type Config ¶
type Config struct { Title string // Required: API title Description string // Optional: API description Version string // Required: API version (e.g., "1.0.0") TermsOfService string // Optional: Terms of service URL Server string // Optional: Base server URL 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 discriminator 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 ExternalDocumentation ¶
type ExternalDocumentation struct { Description string `json:"description,omitempty"` URL string `json:"url"` }
ExternalDocumentation represents OpenAPI 3.1 external documentation
type Generator ¶
type Generator struct {
// contains filtered or unexported fields
}
Generator creates OpenAPI specifications from Chi routers. It provides methods for analyzing route structures, parsing annotations, and generating complete OpenAPI 3.1 specifications.
func NewGenerator ¶
func NewGenerator() *Generator
NewGenerator creates a Generator with a default TypeIndex.
func NewGeneratorWithCache ¶
func NewTestGenerator ¶ added in v0.3.0
func NewTestGenerator() *Generator
NewTestGenerator resets globals and returns a Generator.
func (*Generator) AddWebhook ¶
AddWebhook adds a webhook to the specification
func (*Generator) GenerateSpec ¶
GenerateSpec creates an OpenAPI 3.1 specification from a Chi router. This method analyzes all routes in the router, parses annotations from handlers, and generates schemas for all referenced types. It returns a complete OpenAPI 3.1 specification.
Required configuration fields:
- Title: The API title
- Version: The API version
The method will log warnings for any parsing errors but will continue generation.
type HandlerInfo ¶
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 interface{} `json:"example,omitempty"` Examples map[string]*Example `json:"examples,omitempty"` }
Header represents OpenAPI 3.1 header object
type License ¶
type License struct { Name string // License name (e.g., "MIT", "Apache 2.0") URL string // 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]interface{} `json:"parameters,omitempty"` RequestBody interface{} `json:"requestBody,omitempty"` Description string `json:"description,omitempty"` Server *Server `json:"server,omitempty"` }
Link represents OpenAPI 3.1 link object for describing relationships between operations
type MediaTypeObject ¶
type MyEnum ¶ added in v0.3.0
type MyEnum string
MyEnum is a test enum representing string-based constants.
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"` }
type ParamAnnotation ¶
type RequestBody ¶
type RequestBody struct { Description string `json:"description,omitempty"` Content map[string]MediaTypeObject `json:"content"` Required bool `json:"required,omitempty"` }
type RouteDiscoveryError ¶ added in v0.2.0
RouteDiscoveryError represents an error that occurred during route discovery.
func (*RouteDiscoveryError) Error ¶ added in v0.2.0
func (e *RouteDiscoveryError) Error() string
func (*RouteDiscoveryError) Unwrap ¶ added in v0.2.0
func (e *RouteDiscoveryError) Unwrap() error
type RouteInfo ¶ added in v0.2.0
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 ¶ added in v0.2.0
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 /openapi endpoints) to avoid circular references in the specification.
func InspectRoutes ¶ added in v0.2.0
InspectRoutes walks a Chi router and returns a list of RouteInfo. Returns an error if the router traversal fails or if route analysis encounters issues.
type Schema ¶
type Schema struct { // Basic type information Type string `json:"type,omitempty"` Properties map[string]*Schema `json:"properties,omitempty"` Items *Schema `json:"items,omitempty"` Required []string `json:"required,omitempty"` AdditionalProperties interface{} `json:"additionalProperties,omitempty"` Ref string `json:"$ref,omitempty"` Description string `json:"description,omitempty"` // JSON Schema Draft 2020-12 compliance Format string `json:"format,omitempty"` Pattern string `json:"pattern,omitempty"` Minimum *float64 `json:"minimum,omitempty"` Maximum *float64 `json:"maximum,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 []interface{} `json:"enum,omitempty"` Const interface{} `json:"const,omitempty"` Default interface{} `json:"default,omitempty"` Example interface{} `json:"example,omitempty"` Examples map[string]*Example `json:"examples,omitempty"` // OpenAPI 3.1 composition OneOf []*Schema `json:"oneOf,omitempty"` AnyOf []*Schema `json:"anyOf,omitempty"` AllOf []*Schema `json:"allOf,omitempty"` Not *Schema `json:"not,omitempty"` // Metadata 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"` }
func CreateAllOfSchema ¶
CreateAllOfSchema creates an allOf schema for composition
func CreateAnyOfSchema ¶
CreateAnyOfSchema creates an anyOf schema for union types
func CreateOneOfSchema ¶
CreateOneOfSchema creates a oneOf schema for polymorphic types
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 NewTestSchemaGenerator ¶ added in v0.3.0
func NewTestSchemaGenerator() *SchemaGenerator
NewTestSchemaGenerator resets globals and returns a SchemaGenerator.
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 Spec ¶
type Spec struct { OpenAPI string `json:"openapi"` Info Info `json:"info"` JSONSchemaDialect string `json:"jsonSchemaDialect,omitempty"` // OpenAPI 3.1 feature Servers []Server `json:"servers,omitempty"` Paths map[string]PathItem `json:"paths"` Webhooks Webhooks `json:"webhooks,omitempty"` // OpenAPI 3.1 feature 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 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 ¶ added in v0.2.0
GetQualifiedTypeName returns the appropriate qualified name for a type
func (*TypeIndex) LookupQualifiedType ¶ added in v0.2.0
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.