generator

package
v1.22.1 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package generator provides Go code generation from OpenAPI Specification documents.

The generator creates idiomatic Go code for API clients and server stubs from OAS 2.0 and OAS 3.x specifications. Generated code emphasizes type safety, proper error handling, and clean interfaces.

Quick Start

Generate a client using functional options:

result, err := generator.GenerateWithOptions(
	generator.WithFilePath("openapi.yaml"),
	generator.WithPackageName("petstore"),
	generator.WithClient(true),
)
if err != nil {
	log.Fatal(err)
}
if err := result.WriteFiles("./generated"); err != nil {
	log.Fatal(err)
}

Or use a reusable Generator instance:

g := generator.New()
g.PackageName = "petstore"
g.GenerateClient = true
g.GenerateServer = true
result, _ := g.Generate("openapi.yaml")
result.WriteFiles("./generated")

Generation Modes

The generator supports three modes:

  • Client: HTTP client with methods for each operation
  • Server: Interface definitions and request/response types
  • Types: Schema-only generation (models)

Security Generation

When generating clients, the generator automatically creates security helper functions based on the security schemes defined in the OpenAPI specification. These helpers are generated as ClientOption functions that configure authentication.

Security scheme types and generated helpers:

  • apiKey (header): With{Name}APIKey(key string) ClientOption
  • apiKey (query): With{Name}APIKeyQuery(key string) ClientOption
  • apiKey (cookie): With{Name}APIKeyCookie(key string) ClientOption
  • http/basic: With{Name}BasicAuth(username, password string) ClientOption
  • http/bearer: With{Name}BearerToken(token string) ClientOption
  • oauth2: With{Name}OAuth2Token(token string) ClientOption
  • openIdConnect: With{Name}Token(token string) ClientOption

Enable security generation with WithSecurity(true) or WithGenerateSecurity(true).

OAuth2 Flow Generation

For APIs using OAuth2, the generator can create full OAuth2 client implementations with support for all standard flows:

result, err := generator.GenerateWithOptions(
	generator.WithFilePath("openapi.yaml"),
	generator.WithPackageName("api"),
	generator.WithClient(true),
	generator.WithOAuth2Flows(true),
)

Generated OAuth2 code includes:

  • OAuth2Config struct for client configuration
  • OAuth2Token struct with access/refresh tokens
  • OAuth2Client with flow-specific methods
  • GetAuthorizationURL() for authorization code flow
  • ExchangeCode() to exchange auth codes for tokens
  • GeneratePKCEChallenge() for PKCE challenge generation (RFC 7636)
  • GetAuthorizationURLWithPKCE() for secure authorization with PKCE
  • ExchangeCodeWithPKCE() to exchange auth codes with code verifier
  • GetClientCredentialsToken() for client credentials flow
  • GetPasswordToken() for password flow (with warnings)
  • GetImplicitAuthorizationURL() for implicit flow (deprecated)
  • RefreshToken() for token refresh
  • WithOAuth2AutoRefresh() ClientOption for automatic token refresh

Credential Management

The generator can create credential provider interfaces for flexible authentication:

result, err := generator.GenerateWithOptions(
	generator.WithFilePath("openapi.yaml"),
	generator.WithPackageName("api"),
	generator.WithClient(true),
	generator.WithCredentialMgmt(true),
)

Generated credential code includes:

  • CredentialProvider interface
  • MemoryCredentialProvider for testing
  • EnvCredentialProvider for environment variables
  • CredentialChain for fallback providers
  • WithCredentialProvider() ClientOption

Security Enforcement

Generate security validation middleware for server implementations:

result, err := generator.GenerateWithOptions(
	generator.WithFilePath("openapi.yaml"),
	generator.WithPackageName("api"),
	generator.WithServer(true),
	generator.WithSecurityEnforce(true),
)

Generated enforcement code includes:

  • SecurityRequirement struct
  • OperationSecurityRequirements map
  • SecurityValidator for request validation
  • RequireSecurityMiddleware for enforcement

OpenID Connect Discovery

For APIs using OpenID Connect, generate automatic discovery and configuration:

result, err := generator.GenerateWithOptions(
	generator.WithFilePath("openapi.yaml"),
	generator.WithPackageName("api"),
	generator.WithClient(true),
	generator.WithOIDCDiscovery(true),
)

Generated OIDC code includes:

  • OIDCConfiguration struct
  • OIDCDiscoveryClient for .well-known discovery
  • NewOAuth2ClientFromOIDC() helper

File Splitting for Large APIs

For large APIs (like Microsoft Graph), the generator can split output across multiple files based on operation tags or path prefixes:

result, err := generator.GenerateWithOptions(
	generator.WithFilePath("large-api.yaml"),
	generator.WithPackageName("api"),
	generator.WithClient(true),
	generator.WithMaxLinesPerFile(2000),
	generator.WithSplitByTag(true),
)

File splitting options:

  • WithMaxLinesPerFile(n): Maximum lines per generated file (default: 2000)
  • WithMaxTypesPerFile(n): Maximum types per file (default: 200)
  • WithMaxOperationsPerFile(n): Maximum operations per file (default: 100)
  • WithSplitByTag(bool): Split by operation tags (default: true)
  • WithSplitByPathPrefix(bool): Split by path prefix (default: true)

README Generation

Generate a README.md file documenting the generated code:

result, err := generator.GenerateWithOptions(
	generator.WithFilePath("openapi.yaml"),
	generator.WithPackageName("api"),
	generator.WithClient(true),
	generator.WithReadme(true),
)

The generated README includes:

  • API overview and version info
  • Generated file descriptions
  • Security configuration examples
  • Regeneration command

Type Mapping

OpenAPI types are mapped to Go types as follows:

  • string → string (with format handling: date-time→time.Time, uuid→string, etc.)
  • integer → int64 (int32 for format: int32)
  • number → float64 (float32 for format: float)
  • boolean → bool
  • array → []T
  • object → struct or map[string]T

Optional fields use pointers, and nullable fields in OAS 3.1+ are handled with pointer types or generic Option[T] types (configurable).

Generated Files

The generator produces the following files:

  • types.go: Model structs from components/schemas
  • client.go: HTTP client (when GenerateClient is true)
  • server.go: Server interface (when GenerateServer is true)
  • security_helpers.go: Security ClientOption functions (when GenerateSecurity is true)
  • {name}_oauth2.go: OAuth2 client for each OAuth2 scheme (when GenerateOAuth2Flows is true)
  • credentials.go: Credential provider interfaces (when GenerateCredentialMgmt is true)
  • security_enforce.go: Security validation (when GenerateSecurityEnforce is true)
  • oidc_discovery.go: OIDC discovery client (when GenerateOIDCDiscovery is true)
  • README.md: Documentation (when GenerateReadme is true)

See the exported GenerateResult and GenerateIssue types for complete details.

The generator integrates with other oastools packages:

Example

Example demonstrates basic code generation using functional options

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/generator"
)

func main() {
	// Generate types and client from an OAS 3.0 specification
	result, err := generator.GenerateWithOptions(
		generator.WithFilePath("testdata/petstore-3.0.yaml"),
		generator.WithPackageName("petstore"),
		generator.WithClient(true),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Check for critical issues
	if result.HasCriticalIssues() {
		fmt.Printf("Generation completed with %d critical issue(s)\n", result.CriticalCount)
		return
	}

	fmt.Printf("Successfully generated %d files\n", len(result.Files))
	fmt.Printf("Types: %d, Operations: %d\n", result.GeneratedTypes, result.GeneratedOperations)
	fmt.Printf("Issues: %d info, %d warnings, %d critical\n",
		result.InfoCount, result.WarningCount, result.CriticalCount)
}
Example (ClientAndServer)

Example_clientAndServer demonstrates generating both client and server code

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/generator"
)

func main() {
	g := generator.New()
	g.PackageName = "petstore"
	g.GenerateClient = true
	g.GenerateServer = true
	g.UsePointers = true
	g.IncludeValidation = true

	result, err := g.Generate("testdata/petstore-3.0.yaml")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Generated %d files:\n", len(result.Files))
	for _, file := range result.Files {
		fmt.Printf("  - %s (%d bytes)\n", file.Name, len(file.Content))
	}

	// Write files to output directory
	if err := result.WriteFiles("./generated/petstore"); err != nil {
		log.Fatal(err)
	}
	fmt.Println("Files written to ./generated/petstore")
}
Example (HandleIssues)

Example_handleIssues demonstrates processing generation issues

package main

import (
	"fmt"

	"github.com/erraggy/oastools/generator"
)

func main() {
	result, _ := generator.GenerateWithOptions(
		generator.WithFilePath("complex-api.yaml"),
		generator.WithPackageName("api"),
		generator.WithClient(true),
	)

	// Categorize issues by severity
	for _, issue := range result.Issues {
		switch issue.Severity {
		case generator.SeverityCritical:
			fmt.Printf("CRITICAL [%s]: %s\n", issue.Path, issue.Message)
		case generator.SeverityWarning:
			fmt.Printf("WARNING [%s]: %s\n", issue.Path, issue.Message)
		case generator.SeverityInfo:
			fmt.Printf("INFO [%s]: %s\n", issue.Path, issue.Message)
		}
	}

	fmt.Printf("\nSummary: %d critical, %d warnings, %d info\n",
		result.CriticalCount, result.WarningCount, result.InfoCount)
}
Example (TypesOnly)

Example_typesOnly demonstrates generating only type definitions

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/generator"
)

func main() {
	result, err := generator.GenerateWithOptions(
		generator.WithFilePath("openapi.yaml"),
		generator.WithPackageName("myapi"),
		generator.WithTypes(true),
		generator.WithClient(false),
		generator.WithServer(false),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Access generated types
	if typesFile := result.GetFile("types.go"); typesFile != nil {
		fmt.Printf("Generated types.go with %d bytes\n", len(typesFile.Content))
	}
}
Example (WithFileSplitting)

Example_withFileSplitting demonstrates splitting large APIs into multiple files

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/generator"
)

func main() {
	// For large APIs, split output across multiple files by tag or path prefix
	result, err := generator.GenerateWithOptions(
		generator.WithFilePath("large-api.yaml"),
		generator.WithPackageName("api"),
		generator.WithClient(true),
		generator.WithServer(true),
		generator.WithMaxOperationsPerFile(100), // Split when >100 operations per group
		generator.WithSplitByTag(true),          // Group by operation tags
	)
	if err != nil {
		log.Fatal(err)
	}

	// Files are split by tag: client_users.go, client_orders.go, etc.
	fmt.Printf("Generated %d files for large API\n", len(result.Files))
	for _, file := range result.Files {
		fmt.Printf("  - %s\n", file.Name)
	}
}
Example (WithOAuth2Flows)

Example_withOAuth2Flows demonstrates generating full OAuth2 client implementations

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/generator"
)

func main() {
	// Generate a client with full OAuth2 flow support including PKCE
	result, err := generator.GenerateWithOptions(
		generator.WithFilePath("openapi.yaml"),
		generator.WithPackageName("api"),
		generator.WithClient(true),
		generator.WithOAuth2Flows(true),
	)
	if err != nil {
		log.Fatal(err)
	}

	// OAuth2 files are generated for each OAuth2 security scheme
	// Named: {schemeName}_oauth2.go
	fmt.Printf("Generated %d files with OAuth2 support\n", len(result.Files))

	// Generated OAuth2 code includes:
	// - OAuth2Config for client configuration
	// - OAuth2Client with flow methods:
	//   - GetAuthorizationURL() for authorization code flow
	//   - ExchangeCode() to exchange auth codes for tokens
	//   - GeneratePKCEChallenge() for PKCE (RFC 7636)
	//   - GetClientCredentialsToken() for client credentials
	//   - RefreshToken() for token refresh
	// - WithOAuth2AutoRefresh() for automatic token refresh
	fmt.Println("OAuth2 flows include PKCE support for enhanced security")
}
Example (WithParsedDocument)

Example_withParsedDocument demonstrates using a pre-parsed document

package main

import (
	"fmt"
)

func main() {
	// This example shows how to use a pre-parsed document
	// Useful when you need to parse once and generate multiple times
	// or when integrating with other oastools packages

	// First, parse the document using the parser package
	// parsed, _ := parser.ParseWithOptions(parser.WithFilePath("openapi.yaml"))

	// Then generate using the parsed result
	// result, _ := generator.GenerateWithOptions(
	//     generator.WithParsed(*parsed),
	//     generator.WithPackageName("api"),
	//     generator.WithClient(true),
	// )

	fmt.Println("Pre-parsed document can be used with WithParsed option")
}
Example (WithSecurityHelpers)

Example_withSecurityHelpers demonstrates generating security authentication helpers

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/generator"
)

func main() {
	// Generate a client with security helpers for all defined security schemes
	// Security helpers are generated by default with WithClient(true)
	result, err := generator.GenerateWithOptions(
		generator.WithFilePath("openapi.yaml"),
		generator.WithPackageName("api"),
		generator.WithClient(true),
		generator.WithSecurity(true), // Enabled by default with client
	)
	if err != nil {
		log.Fatal(err)
	}

	// Check for security_helpers.go in generated files
	if secFile := result.GetFile("security_helpers.go"); secFile != nil {
		fmt.Printf("Generated security helpers: %d bytes\n", len(secFile.Content))
	}

	// Generated helpers include:
	// - WithAPIKeyAuth(key string) for apiKey schemes
	// - WithBasicAuth(username, password string) for HTTP basic
	// - WithBearerToken(token string) for HTTP bearer
	// - WithOAuth2Token(token string) for OAuth2 schemes
	fmt.Println("Security helpers provide ClientOption functions for authentication")
}

Index

Examples

Constants

View Source
const (
	// SeverityInfo indicates informational messages about generation choices
	SeverityInfo = severity.SeverityInfo
	// SeverityWarning indicates features that may not generate perfectly
	SeverityWarning = severity.SeverityWarning
	// SeverityError indicates validation errors
	SeverityError = severity.SeverityError
	// SeverityCritical indicates features that cannot be generated
	SeverityCritical = severity.SeverityCritical
)

Variables

This section is empty.

Functions

func GroupNameToTypeName added in v1.22.0

func GroupNameToTypeName(name string) string

GroupNameToTypeName converts a group name to a PascalCase type prefix.

Types

type AliasData added in v1.17.0

type AliasData struct {
	Comment    string
	TypeName   string
	TargetType string
	IsDefined  bool // true for defined type, false for type alias (=)
}

AliasData contains data for a type alias or defined type

type AllOfData added in v1.17.0

type AllOfData struct {
	Comment       string
	TypeName      string
	EmbeddedTypes []string
	Fields        []FieldData
}

AllOfData contains data for AllOf composition

type ClientFileData added in v1.17.0

type ClientFileData struct {
	Header           HeaderData
	DefaultUserAgent string
	Methods          []ClientMethodData
	ParamsStructs    []ParamsStructData
}

ClientFileData contains all data for a client.go file

type ClientMethodData added in v1.17.0

type ClientMethodData struct {
	Comment         string
	MethodName      string
	Params          string
	ResponseType    string
	PathTemplate    string
	PathArgs        []string
	HasQueryParams  bool
	QueryParamsType string
	HasBody         bool
	BodyType        string
	ContentType     string
	MethodBody      string // Complex body handled in Go
}

ClientMethodData contains data for a client method

type CredentialGenerator added in v1.22.0

type CredentialGenerator struct {
	// PackageName is the Go package name for generated code.
	PackageName string
}

CredentialGenerator generates credential management interfaces and implementations.

func NewCredentialGenerator added in v1.22.0

func NewCredentialGenerator(packageName string) *CredentialGenerator

NewCredentialGenerator creates a new CredentialGenerator.

func (*CredentialGenerator) GenerateCredentialsFile added in v1.22.0

func (g *CredentialGenerator) GenerateCredentialsFile() string

GenerateCredentialsFile generates the credentials.go file.

type EnumData added in v1.17.0

type EnumData struct {
	Comment  string
	TypeName string
	BaseType string
	Values   []EnumValueData
}

EnumData contains data for an enum type

type EnumValueData added in v1.17.0

type EnumValueData struct {
	ConstName string
	Type      string
	Value     string
}

EnumValueData contains data for a single enum value

type FieldData added in v1.17.0

type FieldData struct {
	Comment string
	Name    string
	Type    string
	Tags    string
}

FieldData contains data for a struct field

type FileGroup added in v1.22.0

type FileGroup struct {
	// Name is the group name (e.g., "users", "mail").
	// Used for file naming: client_users.go, types_mail.go, etc.
	Name string

	// DisplayName is the human-readable name for documentation.
	DisplayName string

	// Operations contains the operation IDs in this group.
	Operations []string

	// Types contains the type names specific to this group.
	Types []string

	// IsShared is true if this group represents shared types (types.go).
	IsShared bool

	// EstimatedLines is the estimated lines of code for this group.
	EstimatedLines int

	// Tag is the original tag name (if grouped by tag).
	Tag string

	// PathPrefix is the path prefix (if grouped by path).
	PathPrefix string
}

FileGroup represents a group of operations and types that will be generated into a single file.

type FileSplitter added in v1.22.0

type FileSplitter struct {
	// MaxLinesPerFile is the estimated maximum lines per file before splitting.
	// Default: 2000, 0 = no limit
	MaxLinesPerFile int

	// MaxTypesPerFile is the maximum types per file before splitting.
	// Default: 200, 0 = no limit
	MaxTypesPerFile int

	// MaxOperationsPerFile is the maximum operations per file before splitting.
	// Default: 100, 0 = no limit
	MaxOperationsPerFile int

	// SplitByTag enables splitting by operation tags.
	// Default: true
	SplitByTag bool

	// SplitByPathPrefix enables splitting by path prefix as a fallback.
	// Default: true
	SplitByPathPrefix bool
}

FileSplitter analyzes OpenAPI documents and determines how to split generated code across multiple files for large APIs.

func NewFileSplitter added in v1.22.0

func NewFileSplitter() *FileSplitter

NewFileSplitter creates a new FileSplitter with default settings.

func (*FileSplitter) AnalyzeOAS2 added in v1.22.0

func (fs *FileSplitter) AnalyzeOAS2(doc *parser.OAS2Document) *SplitPlan

AnalyzeOAS2 analyzes an OAS 2.0 document and returns a split plan.

func (*FileSplitter) AnalyzeOAS3 added in v1.22.0

func (fs *FileSplitter) AnalyzeOAS3(doc *parser.OAS3Document) *SplitPlan

AnalyzeOAS3 analyzes an OAS 3.x document and returns a split plan.

type GenerateIssue

type GenerateIssue = issues.Issue

GenerateIssue represents a single generation issue or limitation

type GenerateResult

type GenerateResult struct {
	// Files contains all generated files
	Files []GeneratedFile
	// SourceVersion is the detected source OAS version string
	SourceVersion string
	// SourceOASVersion is the enumerated source OAS version
	SourceOASVersion parser.OASVersion
	// SourceFormat is the format of the source file (JSON or YAML)
	SourceFormat parser.SourceFormat
	// PackageName is the Go package name used in generation
	PackageName string
	// Issues contains all generation issues grouped by severity
	Issues []GenerateIssue
	// InfoCount is the total number of info messages
	InfoCount int
	// WarningCount is the total number of warnings
	WarningCount int
	// CriticalCount is the total number of critical issues
	CriticalCount int
	// Success is true if generation completed without critical issues
	Success bool
	// LoadTime is the time taken to load the source data
	LoadTime time.Duration
	// GenerateTime is the time taken to generate code
	GenerateTime time.Duration
	// SourceSize is the size of the source data in bytes
	SourceSize int64
	// Stats contains statistical information about the source document
	Stats parser.DocumentStats
	// GeneratedTypes is the count of types generated
	GeneratedTypes int
	// GeneratedOperations is the count of operations generated
	GeneratedOperations int
}

GenerateResult contains the results of generating code from an OpenAPI specification

func GenerateWithOptions

func GenerateWithOptions(opts ...Option) (*GenerateResult, error)

GenerateWithOptions generates code from an OpenAPI specification using functional options. This provides a flexible, extensible API that combines input source selection and configuration in a single function call.

Example:

result, err := generator.GenerateWithOptions(
    generator.WithFilePath("openapi.yaml"),
    generator.WithPackageName("petstore"),
    generator.WithClient(true),
)

func (*GenerateResult) GetFile

func (r *GenerateResult) GetFile(name string) *GeneratedFile

GetFile returns the generated file with the given name, or nil if not found

func (*GenerateResult) HasCriticalIssues

func (r *GenerateResult) HasCriticalIssues() bool

HasCriticalIssues returns true if there are any critical issues

func (*GenerateResult) HasWarnings

func (r *GenerateResult) HasWarnings() bool

HasWarnings returns true if there are any warnings

func (*GenerateResult) WriteFiles

func (r *GenerateResult) WriteFiles(outputDir string) error

WriteFiles writes all generated files to the specified output directory. The directory is created if it doesn't exist.

type GeneratedFile

type GeneratedFile struct {
	// Name is the file name (e.g., "types.go", "client.go")
	Name string
	// Content is the generated Go source code
	Content []byte
}

GeneratedFile represents a single generated file

func (*GeneratedFile) WriteFile

func (f *GeneratedFile) WriteFile(path string) error

WriteFile writes a single generated file to the specified path.

type GeneratedFileSummary added in v1.22.0

type GeneratedFileSummary struct {
	// FileName is the name of the generated file.
	FileName string

	// Description describes what the file contains.
	Description string

	// LineCount is the number of lines in the file (optional).
	LineCount int
}

GeneratedFileSummary describes a generated file.

type Generator

type Generator struct {
	// PackageName is the Go package name for generated code
	// If empty, defaults to "api"
	PackageName string

	// GenerateClient enables HTTP client generation
	GenerateClient bool

	// GenerateServer enables server interface generation
	GenerateServer bool

	// GenerateTypes enables schema/model type generation
	// This is always true when either client or server generation is enabled
	GenerateTypes bool

	// UsePointers uses pointer types for optional fields
	// Default: true
	UsePointers bool

	// IncludeValidation adds validation tags to generated structs
	// Default: true
	IncludeValidation bool

	// StrictMode causes generation to fail on any issues (even warnings)
	StrictMode bool

	// IncludeInfo determines whether to include informational messages
	IncludeInfo bool

	// UserAgent is the User-Agent string used when fetching URLs
	UserAgent string

	// MaxLinesPerFile is the maximum lines per generated file before splitting.
	// When exceeded, files are split by tag or path prefix.
	// Default: 2000, 0 = no limit
	MaxLinesPerFile int

	// MaxTypesPerFile is the maximum types per generated file before splitting.
	// Default: 200, 0 = no limit
	MaxTypesPerFile int

	// MaxOperationsPerFile is the maximum operations per generated file before splitting.
	// Default: 100, 0 = no limit
	MaxOperationsPerFile int

	// SplitByTag enables splitting files by operation tag.
	// Default: true
	SplitByTag bool

	// SplitByPathPrefix enables splitting files by path prefix as a fallback
	// when tags are not available.
	// Default: true
	SplitByPathPrefix bool

	// GenerateSecurity enables security helper generation.
	// When true, generates ClientOption functions for each security scheme.
	// Default: true when GenerateClient is true
	GenerateSecurity bool

	// GenerateOAuth2Flows enables OAuth2 token flow helper generation.
	// Generates token acquisition, refresh, and authorization code exchange.
	// Default: false
	GenerateOAuth2Flows bool

	// GenerateCredentialMgmt enables credential management interface generation.
	// Generates CredentialProvider interface and built-in implementations.
	// Default: false
	GenerateCredentialMgmt bool

	// GenerateSecurityEnforce enables security enforcement code generation.
	// Generates per-operation security requirements and validation middleware.
	// Default: false
	GenerateSecurityEnforce bool

	// GenerateOIDCDiscovery enables OpenID Connect discovery client generation.
	// Generates OIDC discovery client and auto-configuration helpers.
	// Default: false
	GenerateOIDCDiscovery bool

	// GenerateReadme enables README.md generation in the output directory.
	// The README includes regeneration commands, file listing, and usage examples.
	// Default: true
	GenerateReadme bool
}

Generator handles code generation from OpenAPI specifications

func New

func New() *Generator

New creates a new Generator instance with default settings

func (*Generator) Generate

func (g *Generator) Generate(specPath string) (*GenerateResult, error)

Generate generates code from an OpenAPI specification file or URL

func (*Generator) GenerateParsed

func (g *Generator) GenerateParsed(parseResult parser.ParseResult) (*GenerateResult, error)

GenerateParsed generates code from an already-parsed OpenAPI specification

type GeneratorConfigSummary added in v1.22.0

type GeneratorConfigSummary struct {
	// GenerateTypes indicates if types were generated.
	GenerateTypes bool

	// GenerateClient indicates if client code was generated.
	GenerateClient bool

	// GenerateSecurity indicates if security helpers were generated.
	GenerateSecurity bool

	// GenerateOAuth2Flows indicates if OAuth2 flow helpers were generated.
	GenerateOAuth2Flows bool

	// GenerateCredentialMgmt indicates if credential management was generated.
	GenerateCredentialMgmt bool

	// GenerateSecurityEnforce indicates if security enforcement was generated.
	GenerateSecurityEnforce bool

	// GenerateOIDCDiscovery indicates if OIDC discovery was generated.
	GenerateOIDCDiscovery bool
}

GeneratorConfigSummary describes the generator configuration.

type HeaderData added in v1.17.0

type HeaderData struct {
	PackageName string
	Imports     []string
	Comment     string // Optional file-level comment
}

HeaderData contains data for file header templates

type OAuth2Generator added in v1.22.0

type OAuth2Generator struct {
	// Name is the security scheme name (used for function naming).
	Name string

	// Flows contains the OAuth2 flow configurations.
	Flows *parser.OAuthFlows

	// OAS2Flow is the OAS 2.0 style flow type.
	OAS2Flow string

	// OAS2AuthURL is the OAS 2.0 style authorization URL.
	OAS2AuthURL string

	// OAS2TokenURL is the OAS 2.0 style token URL.
	OAS2TokenURL string

	// OAS2Scopes is the OAS 2.0 style scopes.
	OAS2Scopes map[string]string
}

OAuth2Generator generates OAuth2 token flow helpers.

func NewOAuth2Generator added in v1.22.0

func NewOAuth2Generator(name string, scheme *parser.SecurityScheme) *OAuth2Generator

NewOAuth2Generator creates a new OAuth2Generator from a security scheme.

func (*OAuth2Generator) GenerateOAuth2File added in v1.22.0

func (g *OAuth2Generator) GenerateOAuth2File(packageName string) string

GenerateOAuth2File generates a complete oauth2.go file with token management.

func (*OAuth2Generator) HasAnyFlow added in v1.22.0

func (g *OAuth2Generator) HasAnyFlow() bool

HasAnyFlow returns true if any OAuth2 flow is configured.

type OAuthFlow added in v1.22.0

type OAuthFlow struct {
	AuthorizationURL string
	TokenURL         string
	RefreshURL       string
	Scopes           map[string]string
}

OAuthFlow mirrors parser.OAuthFlow for use in readme generation.

type OAuthFlows added in v1.22.0

type OAuthFlows struct {
	Implicit          *OAuthFlow
	Password          *OAuthFlow
	ClientCredentials *OAuthFlow
	AuthorizationCode *OAuthFlow
}

OAuthFlows mirrors parser.OAuthFlows for use in readme generation.

type OIDCDiscoveryGenerator added in v1.22.0

type OIDCDiscoveryGenerator struct {
	// PackageName is the Go package name for generated code.
	PackageName string
}

OIDCDiscoveryGenerator generates OpenID Connect discovery client code.

func NewOIDCDiscoveryGenerator added in v1.22.0

func NewOIDCDiscoveryGenerator(packageName string) *OIDCDiscoveryGenerator

NewOIDCDiscoveryGenerator creates a new OIDCDiscoveryGenerator.

func (*OIDCDiscoveryGenerator) GenerateOIDCDiscoveryFile added in v1.22.0

func (g *OIDCDiscoveryGenerator) GenerateOIDCDiscoveryFile(discoveryURL string) string

GenerateOIDCDiscoveryFile generates the oidc_discovery.go file.

type OneOfData added in v1.17.0

type OneOfData struct {
	Comment               string
	TypeName              string
	Discriminator         string
	DiscriminatorField    string
	DiscriminatorJSONName string
	Variants              []OneOfVariant
	HasUnmarshal          bool
	UnmarshalCases        []UnmarshalCase
}

OneOfData contains data for OneOf union type

type OneOfVariant added in v1.17.0

type OneOfVariant struct {
	Name string
	Type string
}

OneOfVariant contains data for a OneOf variant

type OperationInfo added in v1.22.0

type OperationInfo struct {
	// OperationID is the unique operation identifier.
	OperationID string

	// Path is the URL path for the operation.
	Path string

	// Method is the HTTP method (GET, POST, etc.).
	Method string

	// Tags are the tags associated with this operation.
	Tags []string

	// ReferencedTypes contains the type names referenced by this operation.
	ReferencedTypes []string

	// EstimatedLines is the estimated lines of generated code.
	EstimatedLines int
}

OperationInfo contains information about an operation for grouping purposes.

type OperationSecurityRequirements added in v1.22.0

type OperationSecurityRequirements map[string][]parser.SecurityRequirement

OperationSecurityRequirements maps operation IDs to their security requirements.

func ExtractOperationSecurityOAS2 added in v1.22.0

func ExtractOperationSecurityOAS2(doc *parser.OAS2Document) OperationSecurityRequirements

ExtractOperationSecurityOAS2 extracts security requirements from an OAS 2.0 document.

func ExtractOperationSecurityOAS3 added in v1.22.0

func ExtractOperationSecurityOAS3(doc *parser.OAS3Document) OperationSecurityRequirements

ExtractOperationSecurity extracts security requirements from an OAS 3.x document.

type Option

type Option func(*generateConfig) error

Option is a function that configures a generate operation

func WithClient

func WithClient(enabled bool) Option

WithClient enables or disables HTTP client generation Default: false

func WithCredentialMgmt added in v1.22.0

func WithCredentialMgmt(enabled bool) Option

WithCredentialMgmt is an alias for WithGenerateCredentialMgmt.

func WithFilePath

func WithFilePath(path string) Option

WithFilePath specifies a file path or URL as the input source

func WithGenerateCredentialMgmt added in v1.22.0

func WithGenerateCredentialMgmt(enabled bool) Option

WithGenerateCredentialMgmt enables or disables credential management interface generation. Generates CredentialProvider interface and built-in implementations. Default: false

func WithGenerateOAuth2Flows added in v1.22.0

func WithGenerateOAuth2Flows(enabled bool) Option

WithGenerateOAuth2Flows enables or disables OAuth2 token flow helper generation. Generates token acquisition, refresh, and authorization code exchange. Default: false

func WithGenerateOIDCDiscovery added in v1.22.0

func WithGenerateOIDCDiscovery(enabled bool) Option

WithGenerateOIDCDiscovery enables or disables OpenID Connect discovery client generation. Generates OIDC discovery client and auto-configuration helpers. Default: false

func WithGenerateReadme added in v1.22.0

func WithGenerateReadme(enabled bool) Option

WithGenerateReadme enables or disables README.md generation in the output directory. The README includes regeneration commands, file listing, and usage examples. Default: true

func WithGenerateSecurity added in v1.22.0

func WithGenerateSecurity(enabled bool) Option

WithGenerateSecurity enables or disables security helper generation. When true, generates ClientOption functions for each security scheme. Default: true

func WithGenerateSecurityEnforce added in v1.22.0

func WithGenerateSecurityEnforce(enabled bool) Option

WithGenerateSecurityEnforce enables or disables security enforcement code generation. Generates per-operation security requirements and validation middleware. Default: false

func WithIncludeInfo

func WithIncludeInfo(enabled bool) Option

WithIncludeInfo enables or disables informational messages Default: true

func WithMaxLinesPerFile added in v1.22.0

func WithMaxLinesPerFile(n int) Option

WithMaxLinesPerFile sets the maximum lines per generated file before splitting. When exceeded, files are split by tag or path prefix. Default: 2000, 0 = no limit

func WithMaxOperationsPerFile added in v1.22.0

func WithMaxOperationsPerFile(n int) Option

WithMaxOperationsPerFile sets the maximum operations per generated file before splitting. Default: 100, 0 = no limit

func WithMaxTypesPerFile added in v1.22.0

func WithMaxTypesPerFile(n int) Option

WithMaxTypesPerFile sets the maximum types per generated file before splitting. Default: 200, 0 = no limit

func WithOAuth2Flows added in v1.22.0

func WithOAuth2Flows(enabled bool) Option

WithOAuth2Flows is an alias for WithGenerateOAuth2Flows.

func WithOIDCDiscovery added in v1.22.0

func WithOIDCDiscovery(enabled bool) Option

WithOIDCDiscovery is an alias for WithGenerateOIDCDiscovery.

func WithPackageName

func WithPackageName(name string) Option

WithPackageName specifies the Go package name for generated code Default: "api"

func WithParsed

func WithParsed(result parser.ParseResult) Option

WithParsed specifies a parsed ParseResult as the input source

func WithPointers

func WithPointers(enabled bool) Option

WithPointers enables or disables pointer types for optional fields Default: true

func WithReadme added in v1.22.0

func WithReadme(enabled bool) Option

WithReadme is an alias for WithGenerateReadme.

func WithSecurity added in v1.22.0

func WithSecurity(enabled bool) Option

WithSecurity is an alias for WithGenerateSecurity.

func WithSecurityEnforce added in v1.22.0

func WithSecurityEnforce(enabled bool) Option

WithSecurityEnforce is an alias for WithGenerateSecurityEnforce.

func WithServer

func WithServer(enabled bool) Option

WithServer enables or disables server interface generation Default: false

func WithSplitByPathPrefix added in v1.22.0

func WithSplitByPathPrefix(enabled bool) Option

WithSplitByPathPrefix enables or disables splitting files by path prefix. This is used as a fallback when tags are not available. Default: true

func WithSplitByTag added in v1.22.0

func WithSplitByTag(enabled bool) Option

WithSplitByTag enables or disables splitting files by operation tag. Default: true

func WithStrictMode

func WithStrictMode(enabled bool) Option

WithStrictMode enables or disables strict mode (fail on any issues) Default: false

func WithTypes

func WithTypes(enabled bool) Option

WithTypes enables or disables type-only generation Note: Types are always generated when client or server is enabled Default: true

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent string for HTTP requests Default: "" (uses parser default)

func WithValidation

func WithValidation(enabled bool) Option

WithValidation enables or disables validation tags in generated structs Default: true

type ParamsStructData added in v1.17.0

type ParamsStructData struct {
	MethodName string
	Fields     []FieldData
}

ParamsStructData contains data for a query params struct

type ReadmeContext added in v1.22.0

type ReadmeContext struct {
	// Timestamp is when the code was generated.
	Timestamp time.Time

	// OastoolsVersion is the version of oastools used.
	OastoolsVersion string

	// SourcePath is the path to the source OAS file(s).
	SourcePath string

	// OASVersion is the OpenAPI version (e.g., "3.0.3", "2.0").
	OASVersion string

	// APITitle is the title from the OAS info section.
	APITitle string

	// APIVersion is the version from the OAS info section.
	APIVersion string

	// APIDescription is the description from the OAS info section.
	APIDescription string

	// CLICommand is the command used to generate this code.
	CLICommand string

	// PackageName is the Go package name.
	PackageName string

	// GeneratedFiles lists all generated files with descriptions.
	GeneratedFiles []GeneratedFileSummary

	// SecuritySchemes describes the security schemes in the API.
	SecuritySchemes []SecuritySchemeSummary

	// SplitInfo contains information about file splitting (if applicable).
	SplitInfo *SplitSummary

	// Config contains the generator configuration used.
	Config *GeneratorConfigSummary
}

ReadmeContext contains all information needed to generate a README.

type ReadmeGenerator added in v1.22.0

type ReadmeGenerator struct{}

ReadmeGenerator generates README.md files for generated code.

func NewReadmeGenerator added in v1.22.0

func NewReadmeGenerator() *ReadmeGenerator

NewReadmeGenerator creates a new ReadmeGenerator.

func (*ReadmeGenerator) GenerateReadme added in v1.22.0

func (g *ReadmeGenerator) GenerateReadme(ctx *ReadmeContext) string

GenerateReadme generates a README.md file.

type RequestTypeData added in v1.17.0

type RequestTypeData struct {
	MethodName string
	Fields     []FieldData
}

RequestTypeData contains data for a request struct

type SecurityEnforceGenerator added in v1.22.0

type SecurityEnforceGenerator struct {
	// PackageName is the Go package name for generated code.
	PackageName string
}

SecurityEnforceGenerator generates security enforcement code.

func NewSecurityEnforceGenerator added in v1.22.0

func NewSecurityEnforceGenerator(packageName string) *SecurityEnforceGenerator

NewSecurityEnforceGenerator creates a new SecurityEnforceGenerator.

func (*SecurityEnforceGenerator) GenerateSecurityEnforceFile added in v1.22.0

func (g *SecurityEnforceGenerator) GenerateSecurityEnforceFile(opSecurity OperationSecurityRequirements, globalSecurity []parser.SecurityRequirement) string

GenerateSecurityEnforceFile generates the security_enforce.go file.

type SecurityHelperGenerator added in v1.22.0

type SecurityHelperGenerator struct {
	// PackageName is the Go package name for generated code.
	PackageName string
}

SecurityHelperGenerator generates security helper code for a client.

func NewSecurityHelperGenerator added in v1.22.0

func NewSecurityHelperGenerator(packageName string) *SecurityHelperGenerator

NewSecurityHelperGenerator creates a new SecurityHelperGenerator.

func (*SecurityHelperGenerator) GenerateSecurityHelpers added in v1.22.0

func (g *SecurityHelperGenerator) GenerateSecurityHelpers(schemes map[string]*parser.SecurityScheme) string

GenerateSecurityHelpers generates ClientOption functions for all security schemes. Returns a complete Go source file with package declaration and imports.

func (*SecurityHelperGenerator) GenerateSecurityImports added in v1.22.0

func (g *SecurityHelperGenerator) GenerateSecurityImports() []string

GenerateSecurityImports returns the imports needed for security helpers.

type SecurityScheme added in v1.22.0

type SecurityScheme struct {
	Type             string
	Description      string
	Name             string
	In               string
	Scheme           string
	BearerFormat     string
	Flows            *OAuthFlows
	OpenIDConnectURL string
	Flow             string // OAS 2.0
}

SecurityScheme mirrors parser.SecurityScheme for use in readme generation.

type SecuritySchemeInfo added in v1.22.0

type SecuritySchemeInfo struct {
	Name         string
	Type         string
	Scheme       string // For HTTP auth
	In           string // For API key
	Description  string
	Scopes       []string // For OAuth2
	FlowTypes    []string // For OAuth2
	DiscoveryURL string   // For OpenID Connect
}

SecuritySchemeInfo contains information about a security scheme for documentation.

func GetSecuritySchemeInfo added in v1.22.0

func GetSecuritySchemeInfo(schemes map[string]*parser.SecurityScheme) []SecuritySchemeInfo

GetSecuritySchemeInfo extracts information about security schemes for documentation.

type SecuritySchemeSummary added in v1.22.0

type SecuritySchemeSummary struct {
	// Name is the security scheme name.
	Name string

	// Type is the security type (apiKey, http, oauth2, openIdConnect).
	Type string

	// Description is the security scheme description.
	Description string

	// Location is where the credential is sent (header, query, cookie) for apiKey.
	Location string

	// Scheme is the HTTP scheme (basic, bearer) for http type.
	Scheme string

	// Flows lists the OAuth2 flows available.
	Flows []string

	// OpenIDConnectURL is the OIDC discovery URL.
	OpenIDConnectURL string
}

SecuritySchemeSummary describes a security scheme.

func ExtractSecuritySchemeSummaries added in v1.22.0

func ExtractSecuritySchemeSummaries(schemes map[string]*SecurityScheme) []SecuritySchemeSummary

ExtractSecuritySchemeSummaries extracts security scheme summaries from a map.

type ServerFileData added in v1.17.0

type ServerFileData struct {
	Header       HeaderData
	Methods      []ServerMethodData
	RequestTypes []RequestTypeData
}

ServerFileData contains all data for a server.go file

type ServerMethodData added in v1.17.0

type ServerMethodData struct {
	Comment      string
	MethodName   string
	ResponseType string
}

ServerMethodData contains data for a server interface method

type Severity

type Severity = severity.Severity

Severity indicates the severity level of a generation issue

type SplitPlan added in v1.22.0

type SplitPlan struct {
	// NeedsSplit is true if the document should be split into multiple files.
	NeedsSplit bool

	// Groups contains the file groups to generate.
	Groups []FileGroup

	// SharedTypes contains type names that are used across multiple groups
	// and should be placed in the main types.go file.
	SharedTypes []string

	// TotalOperations is the total number of operations in the document.
	TotalOperations int

	// TotalTypes is the total number of types/schemas in the document.
	TotalTypes int

	// EstimatedLines is the estimated total lines of generated code.
	EstimatedLines int
}

SplitPlan represents the plan for splitting generated files.

type SplitSummary added in v1.22.0

type SplitSummary struct {
	// WasSplit indicates if files were split.
	WasSplit bool

	// Strategy describes how files were split (by tag, by path prefix).
	Strategy string

	// Groups lists the split groups.
	Groups []string

	// SharedTypesFile is the name of the shared types file (if any).
	SharedTypesFile string
}

SplitSummary describes how files were split.

type StructData added in v1.17.0

type StructData struct {
	Comment             string
	TypeName            string
	OriginalName        string
	Fields              []FieldData
	HasAdditionalProps  bool
	AdditionalPropsType string
}

StructData contains data for a struct type

type TypeDefinition added in v1.17.0

type TypeDefinition struct {
	Kind string // "struct", "enum", "alias", "allof", "oneof"

	Struct *StructData
	Enum   *EnumData
	Alias  *AliasData
	AllOf  *AllOfData
	OneOf  *OneOfData
}

TypeDefinition is a union type for different kind of type definitions

type TypeInfo added in v1.22.0

type TypeInfo struct {
	// Name is the type name.
	Name string

	// ReferencedBy contains operation IDs that reference this type.
	ReferencedBy []string

	// References contains type names this type references.
	References []string

	// EstimatedLines is the estimated lines of generated code.
	EstimatedLines int
}

TypeInfo contains information about a type/schema for grouping purposes.

type TypesFileData added in v1.17.0

type TypesFileData struct {
	Header HeaderData
	Types  []TypeDefinition
}

TypesFileData contains all data for a types.go file

type UnmarshalCase added in v1.17.0

type UnmarshalCase struct {
	Value    string
	TypeName string
}

UnmarshalCase contains data for an unmarshal case

Jump to

Keyboard shortcuts

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