mockzilla-codegen

module
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

README

A gopher with its paws in its pocket
mockzilla-codegen

CI codecov Go Reference License

Go models, HTTP servers, clients and MCP tools from OpenAPI 3.0, 3.1 and 3.2 specs.

Why this one

Every generator works on the petstore. This one works on yours. The specs of Stripe, GitHub, OpenAI and Adyen generate, build and run, and so do 2,200+ other real-world specs.

Specs

  • OpenAPI 3.1 and 3.2, next to 3.0.
  • oneOf and anyOf, with or without a discriminator, nested in each other. In a body, a parameter, a header or a form field.
  • allOf merged into one struct, its limits combined to the strictest.
  • Every inline object gets a named type, however deep. No anonymous structs.
  • $ref into other files, and overlays.
  • A part that cannot be generated gets a warning and is left out. The rest is written.

Parameters and bodies

  • Parameters in every style OpenAPI defines, deepObject and the 3.2 cookie style included.
  • Defaults filled in for parameters the request leaves out.
  • JSON, form and multipart bodies, nested objects included. Binary bodies stream.

Idiomatic Go

  • Fields in the order of the spec. Name clashes resolved for you.
  • A pointer only where a value can be missing, never on a slice or map.
  • runtime.Nullable[T] tells null from absent, so a PATCH can clear a value or leave it as it is. Turn it on for the whole spec or for one field.
  • Validation in plain Go: required fields, patterns, limits, multipleOf, uniqueItems. The server can check every request and response with it.
  • An error response the spec documents is a Go error, on the server and on the client.
  • One file, many files, or a package per part. Any block of the templates can be replaced.

No heavy dependencies

  • Generated code imports the standard library, your router, and a runtime package that uses only the standard library.
  • No YAML parser, logger or third-party JSON library ends up in your binary. Plug one in if you want it.

Server and client

  • 14 routers, net/http's ServeMux among them. Your service stays the same on each.
  • Hooks for OpenTelemetry on server and client: middleware around each operation, and the HTTP client you pass in. Both see the operation name (observability).
  • MCP tools over the client, so an AI assistant can call your API.

Coming from another generator? The migration guides map every flag, config key and extension.

Quick start

Go 1.26 or newer.

go get -tool github.com/mockzilla/mockzilla-codegen/cmd/mockzilla-codegen
go tool mockzilla-codegen generate openapi.yaml               # models in ./gen.go
go tool mockzilla-codegen generate openapi.yaml -server chi   # and a chi server
go tool mockzilla-codegen generate -c codegen.yaml            # what the config lists

Example

This spec:

paths:
  /pets/{id}:
    get:
      operationId: getPet
      parameters:
        - {name: id, in: path, required: true, schema: {type: integer}}
      responses:
        "200":
          description: ok
          content: {application/json: {schema: {$ref: "#/components/schemas/Pet"}}}
components:
  schemas:
    Pet:
      type: object
      required: [id, name]
      properties:
        id: {type: integer}
        name: {type: string, maxLength: 64}
        tag: {type: string}

gives this, among other code:

type Pet struct {
	ID   int     `json:"id"`
	Name string  `json:"name"`
	Tag  *string `json:"tag,omitempty"`
}

func (p Pet) Validate() error {
	var errs validation.Errors
	errs.Append("name", validation.MaxLength(p.Name, 64))
	return errs.Err()
}

type ServiceInterface interface {
	// GetPet handles GET /pets/{id}.
	GetPet(ctx context.Context, opts *GetPetServiceRequestOptions) (*GetPetResponseData, error)
}

You implement the service. The generated router decodes the request and writes the response:

type pets struct{}

func (pets) GetPet(ctx context.Context, opts *api.GetPetServiceRequestOptions) (*api.GetPetResponseData, error) {
	return api.NewGetPetResponseData(&api.Pet{ID: opts.PathParams.ID, Name: "Rex"}), nil
}

http.ListenAndServe(":8080", api.NewRouter(pets{}))

Docs

Guide What it covers
Getting started install, commands, checking generated files in CI, the runtime guard
Configuration every key, output files, defaults
Types how schemas become Go types: unions, allOf, nullable values
Naming how names are built and how clashes are resolved
Validation the generated checks for requests and responses
Error types response types that are Go errors
Extensions the x-go-* extensions and masking of sensitive values
Server the service interface, the HTTP adapter, 14 routers, starter files
Client one method per operation, envelopes, streams
MCP MCP tools over the client
Observability tracing and metrics with OpenTelemetry, on server and client
Templates replacing template blocks, extra files from your own templates
Migration moving from another generator

Contributing

Issues and pull requests are welcome. CONTRIBUTING.md lists the make targets, the checks a pull request has to pass, and how to add a router.

License

MIT, see LICENSE. The Go gopher was designed by Renée French and is licensed under CC BY 4.0. The gopher above is a new drawing of it.

Directories

Path Synopsis
cmd
mockzilla-codegen command
Command mockzilla-codegen generates Go code from OpenAPI specs.
Command mockzilla-codegen generates Go code from OpenAPI specs.
internal
bundle
Package bundle turns a spec split over files and URLs into one document.
Package bundle turns a spec split over files and URLs into one document.
diag
Package diag is how every stage reports a problem in a spec: a severity, a code, a message, and where in the spec it is.
Package diag is how every stage reports a problem in a spec: a severity, a code, a message, and where in the spec it is.
ecma
Package ecma writes ECMA-262 patterns in Go's regexp syntax, keeping their ECMA-262 meaning.
Package ecma writes ECMA-262 patterns in Go's regexp syntax, keeping their ECMA-262 meaning.
extension
Package extension reads the x-* extensions mockzilla-codegen knows into typed values.
Package extension reads the x-* extensions mockzilla-codegen knows into typed values.
gen/client
Package client turns the operations of the Go model into an HTTP client: the client type with its options, the request options of every operation, the methods that call the API, and the response envelopes of the HasEnvelopes methods.
Package client turns the operations of the Go model into an HTTP client: the client type with its options, the request options of every operation, the methods that call the API, and the response envelopes of the HasEnvelopes methods.
gen/mcp
Package mcp turns the operations of the Go model into MCP tools that call the generated client: the tools type that registers them on a server of the official Go SDK, one tool definition and handler per operation, and the input type of every tool.
Package mcp turns the operations of the Go model into MCP tools that call the generated client: the tools type that registers them on a server of the official Go SDK, one tool definition and handler per operation, and the input type of every tool.
gen/models
Package models turns the declarations of the Go model into the data its templates render.
Package models turns the declarations of the Go model into the data its templates render.
gen/operation
Package operation holds what the server, the client and the MCP generators share about an operation: the fields its parameters and bodies go in, the Go type of a body, the status code a response key names, how the runtime names a parameter's style, the encoding of a form body, and the parts the types of an operation are declared in.
Package operation holds what the server, the client and the MCP generators share about an operation: the fields its parameters and bodies go in, the Go type of a body, the status code a response key names, how the runtime names a parameter's style, the encoding of a form body, and the parts the types of an operation are declared in.
gen/server
Package server turns the operations of the Go model into a server: the service contract a service implements, the HTTP adapter that calls it, the router of one framework, and the scaffold files a project starts from.
Package server turns the operations of the Go model into a server: the service contract a service implements, the HTTP adapter that calls it, the router of one framework, and the scaffold files a project starts from.
gen/server/framework
Package framework is what the router of one HTTP framework needs from the generator, and what every framework shares.
Package framework is what the router of one HTTP framework needs from the generator, and what every framework shares.
gen/server/framework/beego
Package beego is the router for github.com/beego/beego/v2.
Package beego is the router for github.com/beego/beego/v2.
gen/server/framework/chi
Package chi is the router for github.com/go-chi/chi.
Package chi is the router for github.com/go-chi/chi.
gen/server/framework/echo
Package echo is the router for github.com/labstack/echo, whose handlers take an echo.Context and return an error.
Package echo is the router for github.com/labstack/echo, whose handlers take an echo.Context and return an error.
gen/server/framework/echov5
Package echov5 is the router for github.com/labstack/echo/v5, whose handlers take an *echo.Context and return an error.
Package echov5 is the router for github.com/labstack/echo/v5, whose handlers take an *echo.Context and return an error.
gen/server/framework/fasthttp
Package fasthttp is the router for github.com/fasthttp/router over github.com/valyala/fasthttp.
Package fasthttp is the router for github.com/fasthttp/router over github.com/valyala/fasthttp.
gen/server/framework/fiber
Package fiber is the router for github.com/gofiber/fiber/v3.
Package fiber is the router for github.com/gofiber/fiber/v3.
gen/server/framework/gin
Package gin is the router for github.com/gin-gonic/gin.
Package gin is the router for github.com/gin-gonic/gin.
gen/server/framework/goframe
Package goframe is the router for github.com/gogf/gf/v2.
Package goframe is the router for github.com/gogf/gf/v2.
gen/server/framework/gorillamux
Package gorillamux is the router for github.com/gorilla/mux.
Package gorillamux is the router for github.com/gorilla/mux.
gen/server/framework/gozero
Package gozero is the router for the rest package of github.com/zeromicro/go-zero: the router of its rest server, which rest.WithRouter gives one.
Package gozero is the router for the rest package of github.com/zeromicro/go-zero: the router of its rest server, which rest.WithRouter gives one.
gen/server/framework/hertz
Package hertz is the router for github.com/cloudwego/hertz.
Package hertz is the router for github.com/cloudwego/hertz.
gen/server/framework/iris
Package iris is the router for github.com/kataras/iris/v12.
Package iris is the router for github.com/kataras/iris/v12.
gen/server/framework/kratos
Package kratos is the router for the HTTP transport of github.com/go-kratos/kratos/v2, whose handlers take a kratos Context and return an error.
Package kratos is the router for the HTTP transport of github.com/go-kratos/kratos/v2, whose handlers take a kratos Context and return an error.
gen/server/framework/stdhttp
Package stdhttp is the router for http.ServeMux of the standard library, with its method and wildcard patterns.
Package stdhttp is the router for http.ServeMux of the standard library, with its method and wildcard patterns.
gocode
Package gocode writes Go source text: type expressions as a given file spells them, imports, comments, tags and literals, and formats the result.
Package gocode writes Go source text: type expressions as a given file spells them, imports, comments, tags and literals, and formats the result.
gomodel
Package gomodel turns the spec IR into a typed Go model: named declarations, fields, pointers, enums, maps and merged allOf schemas.
Package gomodel turns the spec IR into a typed Go model: named declarations, fields, pointers, enums, maps and merged allOf schemas.
itest
Package itest holds the parts of the integration test that can be unit tested: collecting specs, the sandbox module, running and building jobs, the result cache, known failures and the report.
Package itest holds the parts of the integration test that can be unit tested: collecting specs, the sandbox module, running and building jobs, the result cache, known failures and the report.
jsonschema
Package jsonschema writes schemas of the spec IR as JSON Schema 2020-12 documents, the way MCP tools describe their input.
Package jsonschema writes schemas of the spec IR as JSON Schema 2020-12 documents, the way MCP tools describe their input.
layout
Package layout places generated parts in files and gives each folder its package name and import path.
Package layout places generated parts in files and gives each folder its package name and import path.
naming
Package naming turns spec names into Go names and settles clashes between them.
Package naming turns spec names into Go names and settles clashes between them.
oasdoc
Package oasdoc edits an OpenAPI document as a YAML node tree, addressed by JSON pointers.
Package oasdoc edits an OpenAPI document as a YAML node tree, addressed by JSON pointers.
prepare
Package prepare turns the input spec into the one the generator reads: files bundled, overlays applied, then filtered, simplified and pruned.
Package prepare turns the input spec into the one the generator reads: files bundled, overlays applied, then filtered, simplified and pruned.
provider
Package provider is the boundary between the generator and the library that reads OpenAPI.
Package provider is the boundary between the generator and the library that reads OpenAPI.
provider/libopenapi
Package libopenapi implements provider.Provider and is the only importer of libopenapi.
Package libopenapi implements provider.Provider and is the only importer of libopenapi.
render
Package render runs the templates of every generator and puts their output together into files.
Package render runs the templates of every generator and puts their output together into files.
spec
Package spec is the provider-neutral OpenAPI IR: ordered slices only, not changed after build.
Package spec is the provider-neutral OpenAPI IR: ordered slices only, not changed after build.
transform
Package transform filters, simplifies and prunes a spec as a YAML node tree.
Package transform filters, simplifies and prunes a spec as a YAML node tree.
pkg
cli
Package cli is the mockzilla-codegen command line, for its own binary and for programs that run it as one of their commands.
Package cli is the mockzilla-codegen command line, for its own binary and for programs that run it as one of their commands.
codegen
Package codegen generates Go models, HTTP servers, clients and MCP tools from OpenAPI specs.
Package codegen generates Go models, HTTP servers, clients and MCP tools from OpenAPI specs.
config
Package config loads, checks and describes the mockzilla-codegen config file.
Package config loads, checks and describes the mockzilla-codegen config file.
runtime
Package runtime holds the helpers generated code imports.
Package runtime holds the helpers generated code imports.
runtime/httpclient
Package httpclient builds and sends the requests of a generated client and reads its responses.
Package httpclient builds and sends the requests of a generated client and reads its responses.
runtime/httpserver
Package httpserver holds the errors, error handlers, operation middleware and response writing of a generated server.
Package httpserver holds the errors, error handlers, operation middleware and response writing of a generated server.
runtime/mask
Package mask hides sensitive values, for logs and other output.
Package mask hides sensitive values, for logs and other output.
runtime/mcptool
Package mcptool holds what generated MCP tools call: their input, result and error.
Package mcptool holds what generated MCP tools call: their input, result and error.
runtime/validation
Package validation checks values against the constraints of a spec and collects what fails.
Package validation checks values against the constraints of a spec and collects what fails.

Jump to

Keyboard shortcuts

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