generator

package
v1.19.1 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 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)

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.

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 (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

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
	// SeverityCritical indicates features that cannot be generated
	SeverityCritical = severity.SeverityCritical
)

Variables

This section is empty.

Functions

This section is empty.

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 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 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 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 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 HeaderData added in v1.17.0

type HeaderData struct {
	PackageName string
	Imports     []string
}

HeaderData contains data for file header templates

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 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 WithFilePath

func WithFilePath(path string) Option

WithFilePath specifies a file path or URL as the input source

func WithIncludeInfo

func WithIncludeInfo(enabled bool) Option

WithIncludeInfo enables or disables informational messages Default: true

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 WithServer

func WithServer(enabled bool) Option

WithServer enables or disables server interface generation Default: false

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 RequestTypeData added in v1.17.0

type RequestTypeData struct {
	MethodName string
	Fields     []FieldData
}

RequestTypeData contains data for a request struct

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 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 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