codegen

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package codegen generates Go models, HTTP servers, clients and MCP tools from OpenAPI specs.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrWrite        = errors.New("write generated file")
	ErrFramework    = errors.New("no router for the framework")
	ErrTemplateFile = errors.New("read template file")
	ErrExtraFile    = errors.New("extra file")
	ErrNameClash    = errors.New("name declared twice")
)

Functions

func Version

func Version() string

Version returns the version of this module in the running binary, or "dev" for local builds.

Types

type API

type API struct {
	Package     string
	Service     TypeRef
	Operations  []Operation
	Types       []TypeRef
	UserContext map[string]any
}

API is what the template of an extra file sees of the generated code once names are resolved: the package of the default output file, the service interface, which is empty without a server, every operation, every declared type and the config's user-context. It only ever gains fields.

type Body

type Body struct {
	ContentType string
	Field       string
	Type        TypeRef
}

Body is one request body of an operation: its media type, the field of the request options that holds it, server and client alike, and the type of that field.

type Diagnostic

type Diagnostic struct {
	Severity Severity
	Code     string
	Pointer  string
	File     string
	Line     int
	Col      int
	Message  string
}

Diagnostic is a problem found in the spec, or in what the config asks of it. Pointer is a JSON pointer into the prepared spec; File, Line and Col say where it is in the source, Line and Col 0 when unknown. A problem that has no place in the spec has none of them.

func Prepare

func Prepare(ctx context.Context, cfg *config.Config, opts ...Option) ([]byte, []Diagnostic, error)

Prepare returns the spec the generator reads: refs to other files bundled in, overlays applied, then filtered, simplified and pruned as cfg says. A spec no step changes comes back byte for byte.

func (Diagnostic) String

func (d Diagnostic) String() string

String is the line the command prints: file:line:col: severity code: message [pointer], with each place left out when unknown.

type File

type File struct {
	Path          string
	Package       string
	Parts         []string
	Kind          FileKind
	IsOverwritten bool
	Content       []byte
}

File is one generated file. Path is resolved against the config folder; Parts lists the parts it holds, such as models.types. IsOverwritten is set on a scaffold that server.scaffold.overwrite lets Write replace.

type FileKind

type FileKind int
const (
	// FileGenerated is rewritten on every run.
	FileGenerated FileKind = iota
	// FileScaffold is a starter file, written only when missing unless told to overwrite.
	FileScaffold
)

type Operation

type Operation struct {
	ID                   string
	Method               string
	Path                 string
	Summary              string
	Tags                 []string
	HasOptions           bool
	IsRouted             bool
	RequestOptions       TypeRef
	ResponseData         TypeRef
	ClientRequestOptions TypeRef
	ClientResponse       TypeRef
	Bodies               []Body
	Responses            []Response
	Success              *Response
}

Operation is one operation or webhook of the spec. ID is its Go name, which the handlers report as the operation ID; HasOptions says whether it takes parameters or a body, IsRouted whether the router registers it. RequestOptions and ResponseData are the types of the service contract, empty without a server; ClientRequestOptions is what the client method takes and ClientResponse the envelope its WithResponse method returns, empty without a client or without envelopes. Bodies are the request bodies, in spec order. Responses come in the order of the generated code: codes, ranges, other keys, then default. Success points to the first of them with a Code from 200 to 299, nil without one.

type Option

type Option func(*options)

func WithSpec

func WithSpec(data []byte) Option

WithSpec passes the spec in memory instead of reading spec.path. When spec.path is set it still names the spec, so refs to other files resolve next to it; otherwise they resolve against the config's folder.

type Response

type Response struct {
	Status       string
	Code         int
	ContentType  string
	Body         TypeRef
	IsRaw        bool
	IsStream     bool
	Constructor  TypeRef
	HasStatusArg bool
}

Response is one response of an operation. Status is its key as the spec writes it, such as 200, 2XX or default. Code is the status code the generated code reads from that key: the key when it is a number, the first digit times 100 when it has three characters and starts with a digit, else 0. ContentType and Body are those of its JSON body, else of its first one; Body is empty without one. IsRaw is set when the body has no schema: any, a string or bytes. Constructor is the function that makes the response data of this status, empty without a server: it takes the status first when HasStatusArg is set, which is when the key is no number, then the body when there is one. With IsStream it takes an iter.Seq of Body, one frame.

type Result

type Result struct {
	Files       []File
	Diagnostics []Diagnostic
}

Result is what Generate made: every file with its content, and what the spec and generation reported, sorted by position.

func Generate

func Generate(ctx context.Context, cfg *config.Config, opts ...Option) (*Result, error)

Generate reads the spec cfg names, or the one WithSpec gives, and returns the files to write. cfg must come from config.Load or config.Parse, which fill in the defaults.

type Severity

type Severity int
const (
	SeverityInfo Severity = iota
	SeverityWarning
	SeverityError
)

func (Severity) String

func (s Severity) String() string

type TypeRef

type TypeRef struct {
	Name       string
	Package    string
	ImportPath string
}

TypeRef is a Go type, or a function such as a response constructor. Name is the type as the package that declares it writes it, Package and ImportPath are those of the identifier in it. With an ImportPath, Name is an identifier, or a pointer, slice, array, map or channel around one, such as []Pet, and Package, when set, is the package's name; without one the type needs no import, Name is written as it is, such as func() any, and Package is empty. A type the generator declares has neither when the output is one package outside a module.

func (TypeRef) Elem

func (t TypeRef) Elem() TypeRef

Elem is the type t points to, in the package of t: Pet for *Pet. It is empty when t is no pointer.

type WriteAction

type WriteAction int
const (
	ActionWrite WriteAction = iota
	ActionSkip
)

func (WriteAction) String

func (a WriteAction) String() string

type WriteOptions

type WriteOptions struct {
	DryRun bool
}

WriteOptions control Write. DryRun reports what Write would do and writes nothing.

type WriteReport

type WriteReport struct {
	Path   string
	Action WriteAction
}

WriteReport says what Write did with one file.

func Write

func Write(res *Result, opts WriteOptions) ([]WriteReport, error)

Write writes the files of res, making folders as needed. A scaffold that exists is skipped unless its IsOverwritten is set. It stops at the first failure and returns the reports of the files before it.

Jump to

Keyboard shortcuts

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