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)
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)
See the exported GenerateResult and GenerateIssue types for complete details.
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 (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")
}
Index ¶
- Constants
- type GenerateIssue
- type GenerateResult
- type GeneratedFile
- type Generator
- type Option
- func WithClient(enabled bool) Option
- func WithFilePath(path string) Option
- func WithIncludeInfo(enabled bool) Option
- func WithPackageName(name string) Option
- func WithParsed(result parser.ParseResult) Option
- func WithPointers(enabled bool) Option
- func WithServer(enabled bool) Option
- func WithStrictMode(enabled bool) Option
- func WithTypes(enabled bool) Option
- func WithUserAgent(ua string) Option
- func WithValidation(enabled bool) Option
- type Severity
Examples ¶
Constants ¶
const ( // SeverityInfo indicates informational messages about generation choices SeverityInfo = severity.SeverityInfo // SeverityWarning indicates features that may not generate perfectly SeverityWarning = severity.SeverityWarning // SeverityCritical indicates features that cannot be generated SeverityCritical = severity.SeverityCritical )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type GenerateIssue ¶
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 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
}
Generator handles code generation from OpenAPI specifications
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 Option ¶
type Option func(*generateConfig) error
Option is a function that configures a generate operation
func WithClient ¶
WithClient enables or disables HTTP client generation Default: false
func WithFilePath ¶
WithFilePath specifies a file path or URL as the input source
func WithIncludeInfo ¶
WithIncludeInfo enables or disables informational messages Default: true
func WithPackageName ¶
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 ¶
WithPointers enables or disables pointer types for optional fields Default: true
func WithServer ¶
WithServer enables or disables server interface generation Default: false
func WithStrictMode ¶
WithStrictMode enables or disables strict mode (fail on any issues) Default: false
func WithTypes ¶
WithTypes enables or disables type-only generation Note: Types are always generated when client or server is enabled Default: true
func WithUserAgent ¶
WithUserAgent sets the User-Agent string for HTTP requests Default: "" (uses parser default)
func WithValidation ¶
WithValidation enables or disables validation tags in generated structs Default: true