Generated-code customization
Generated-code customization controls how an OpenAPI description becomes usable Go code without changing the source API contract. The generator combines output policy, schema and field controls, type choices, template overrides, and package rules before it emits models, clients, and server code. This page focuses on those choices; see Customization and extensions for the wider set of extension points.
Customization model
Customization takes place between the loaded OpenAPI document and the final Go package. Each surface answers a different question about the generated result.
| Surface | Main question | Typical result |
|---|---|---|
| Output options | Which generated forms, names, and schema shapes should be used? | Selected operations, model names, named inline schemas, response names, media-type names, optional-value rules, and formatting |
| User templates | How should a generated section be written? | A project-specific client, model, import block, or server section |
| Struct-tag controls | How should fields behave for encoders and binders? | json, form, yaml, or project-specific tags |
| Type mappings | Which Go type represents an OpenAPI type or format? | A local type or an imported type such as a date type |
| Package and import decisions | Where does a referenced Go name come from? | The current package, an external generated package, or an added import |
The generator validates these choices before it writes the result. A valid OpenAPI document can still produce an unusable package if a custom type, import, template, or generated name does not match the surrounding Go code. Some cross-option combinations produce warnings instead of errors because a sibling configuration may provide the missing declaration.
Customization flow
The source description and customization choices pass through selection, type preparation, rendering, and import resolution to form one Go package.
flowchart LR
A[OpenAPI document] --> B[Load and select API content]
C[Configuration] --> B
C --> D[Choose templates, tags, types, and packages]
B --> E[Build models and operation data]
D --> E
E --> F[Render generated sections]
D --> F
F --> G[Resolve imports and format Go]
G --> H[Generated package]
The same choice can affect more than one section. A type mapping changes a model field and the imports needed by that model. A struct-tag rule can affect both schema fields and strict request parameter objects. Strict server templates also shape how generated response objects write headers, bodies, and streaming content for each selected framework.
User template overrides
User templates replace named built-in templates when the generator renders a section. They are useful when the generated contract is correct but a project needs a different declaration shape, comment style, helper method, or framework section. The override key must exactly match the built-in template name, such as client-with-responses.tmpl or typedef.tmpl.
Template text can come from three sources:
- A local file path, which is the best choice for a versioned and repeatable build.
- An HTTPS URL, which can make the build depend on a changing remote resource.
- An inline multi-line value in the configuration file.
Overrides use Go text/template syntax and the generator's registered template functions. A template must produce a complete and valid part of the target Go package. The generator loads and parses user templates before it renders code, so syntax or data-shape errors stop generation rather than silently producing a partial result. See Template rendering for the broader template model.
Framework server output shares common sections and has framework-specific sections. An override to a shared template can therefore affect more than one generated server form. Keep such overrides narrow when the same configuration can select different server frameworks. The strict server interface templates define the response-object contract for the standard HTTP server and framework adapters. Their generated response visitors set status and headers, serialize supported bodies, copy raw bodies, and flush configured streaming responses. Changes to these templates can therefore change the runtime behavior promised by generated server code.
The framework-specific strict handler templates adapt the same operation flow to standard HTTP, Echo, Fiber, Gin, and Iris. They turn framework requests into generated request objects, run operation middleware, invoke the strict server interface, and pass the result to the generated response visitor. Each adapter also keeps its framework's request and error-handling contract, so a change to one template can change that framework's generated runtime behavior without changing the OpenAPI contract.
References: pkg/…/strict-http.tmpl• L1-150 pkg/…/strict-echo.tmpl• L1-132 pkg/…/strict-fiber.tmpl• L1-121 pkg/…/strict-gin.tmpl• L1-179 pkg/…/strict-iris.tmpl• L1-137
Struct-tag controls
Struct-tag controls define the field metadata that Go encoders and request binders use. The default output provides JSON tags and form tags where form binding needs them. YAML tags can be enabled with the legacy yaml-tags option or defined directly through struct-tags.
output-options.struct-tags adds or replaces tag rules by tag name. Each rule is a Go template over the field data below:
| Value | Meaning |
|---|---|
.FieldName | Name used by the OpenAPI field |
.IsOptional | The field is not required |
.OmitEmpty | The field should use empty-value omission |
.OmitZero | The field should use zero-value omission |
.NeedsFormTag | The field is used by form-style input |
A rule that renders an empty value removes that tag for the field. A user rule with the same name replaces the default rule. New tag names add metadata, and generated tags are written in alphabetical order.
Per-field OpenAPI extensions are applied after the configured rules. x-oapi-codegen-extra-tags adds or replaces tag values, while x-go-json-ignore forces the JSON tag to -. The x-omitempty and x-omitzero controls affect the computed omission values that templates receive. Parameter-level extra tags take precedence over schema-level extra tags for strict request objects.
Type mappings
Type mappings choose the Go representation for primitive OpenAPI types and their formats. A mapping has a default for a base type and optional format-specific entries. A format entry wins when it exists. Otherwise, the base default applies.
User mappings merge on top of the built-in mappings. A project can change one default or one format without restating the full mapping. An entry can also name an import that the generated package needs. The chosen type must exist in the current package or in that imported package.
For example, a project can map all OpenAPI number values to int64 and map the date format to a local CustomDateHandler type:
output-options:
type-mapping:
number:
default:
type: int64
formats:
date:
type: CustomDateHandler
Type mappings apply to generated model and operation types. They do not replace a more specific schema-level Go type control. Use OpenAPI vendor extensions when one schema needs a type or name that should not become a global type rule.
Output options
Output options shape the generated API while preserving the OpenAPI source. They are the right place for policy that applies to a generation run rather than to one schema or field. For the full configuration reference, see Generator configuration.
| Need | Relevant option group | Effect |
|---|---|---|
| Limit the API surface | Include or exclude tags, operation IDs, or schemas | Keeps selected operations or models out of the result |
| Control Go names | Name normalizer, additional initialisms, client type name, response suffix | Changes exported names and helps fit local naming rules |
| Control optional values | Optional-pointer preferences, nullable type, omission settings | Changes how absence, null, and zero values appear in Go |
| Control anonymous schema names | generate-types-for-anonymous-schemas | Gives inline schemas named Go types instead of anonymous structs |
| Control type declarations | Type-alias and type-name collision options | Changes declaration shape or resolves duplicate generated names |
| Control media-type names and coverage | content-types | Adds or replaces media-type name tags and can create models for custom media types |
| Control streaming behavior | streaming-content-types | Selects response media types that use flush-per-chunk output |
| Control generated helpers | Enum validation, response getters, response content helpers | Removes or adds convenience methods |
| Control schema input | overlay | Applies an OpenAPI Overlay before generation without changing the source document |
| Control post-processing | skip-fmt and pruning options | Changes formatting or which unused API parts remain |
Options can also select how newer schema forms become Go declarations. Enum-via-oneOf detection can be disabled, union accessors can use stricter or more lenient property checks, and selected OpenAPI types can avoid aliases. Type-name collision resolution can add component-based suffixes when different API sections would otherwise produce the same Go name. Response helper options control whether generated response objects expose content-type, byte, or body-getter helpers.
Options that change type declarations must agree across configurations that write to one Go package. generate-types-for-anonymous-schemas names inline schemas, but the model-producing configuration must emit those declarations. The generator warns when operation code refers to hoisted types while the current configuration does not emit models. The warning is safe to ignore only when a sibling configuration emits those declarations into the same package with matching settings.
content-types maps short names to media-type patterns. A match changes the suffix used in generated request and response type names while the media type still controls wire encoding. User entries replace built-in entries with the same name, and an empty pattern list disables a built-in name. A custom match can make models and named request bodies appear for a media type that is not built in. Client responses get typed fields only when the client knows how to deserialize that media type. Other responses keep the raw body. A media type that matches more than one short name is invalid because the generator cannot choose one type-name suffix.
streaming-content-types adds regular-expression patterns to the built-in streaming set. Invalid patterns stop configuration validation. The option changes the generated response path for matching media types. It does not rename the types or change the source API description. In strict server output, matching response bodies are sent in chunks and flushed when the selected server runtime supports flushing. Unsupported flush support falls back to a normal body copy where the framework permits it.
Some options are contracts between generation runs. Named types for anonymous schemas must be emitted by the model-producing configuration when operation code refers to them. When several configurations write to one Go package, name and type options must agree so declarations and references have the same shape. The generator warns when a configuration hoists anonymous types but does not emit models. The warning is safe to ignore only when a sibling configuration emits those declarations into the same package.
Package and import decisions
Package and import decisions connect generated names to real Go packages. package sets the package that receives the generated declarations. additional-imports adds imports for code introduced by a user template or another project-level rule, and an entry can provide the alias used by the generated code.
The generated import block also reflects selected server support and external references. A selected router adds its framework package. Standard-library HTTP output marks the file for Go 1.22 or newer. Shared support imports appear only when the emitted code needs them.
import-mapping handles external OpenAPI references. Its key is the external document path or URL exactly as written in the $ref. A JSON pointer is not a valid mapping key because references within the same document stay in the package being generated. An external package receives a deterministic import alias unless the mapping supplies one with the package path.
Schema-level Go type controls provide a second import path. x-go-type names an existing Go type, and x-go-type-import identifies the package that provides it. The import is meaningful only when the type override is used. These controls are useful when a schema maps to a domain type that is not generated from the OpenAPI document.
The import set is assembled from generated code, external references, selected server framework support, additional imports, and type overrides. The final formatting step removes imports that the resulting Go source does not use. For external-reference rules and multi-file API layouts, see OpenAPI loading and references.
Change checklist
When these files or sections are changed, remember to consider these:
- Keep every
user-templateskey aligned with the built-in template name and with the data shape that the generator passes to that template. - If a custom template introduces a qualified Go type, add its package through
additional-importsor another import-producing rule. Do not rely on the formatter to invent a missing import. - When changing a strict server template, check all selected server frameworks. Handler rules must keep request binding, operation middleware, response dispatch, and framework error handling consistent. Response rules must keep status, headers, body encoding, raw-body copying, and streaming behavior consistent with the framework contract.
- When changing a struct-tag rule, check both schema fields and strict request parameter fields. Their legacy YAML behavior is not identical.
- When changing a type mapping, check the local or external package that defines the mapped type and all generated models that use the affected OpenAPI format.
- When changing
content-types, check that each short name is a valid Go identifier fragment, that patterns do not overlap for any media type used by one operation, and that unsupported response media types are expected to remain raw. - When changing
streaming-content-types, check that the patterns remain valid and that matching responses still meet the runtime's streaming contract. - When changing
import-mapping, keep each key identical to the external$refdocument path and generate the referenced package with compatible declarations. - When changing naming, optional-pointer, or anonymous-type options across split configurations, apply the same choice to the configurations that declare and reference the affected types.
- Pin remote user templates to a tag or commit when the generated package must be reproducible.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A user-template key does not exactly match a built-in template name | The intended section keeps its built-in rendering | Copy the exact template filename into user-templates |
| A custom template has invalid syntax or refers to unavailable template data | Generation stops before output is produced | Parse the template as part of the generation workflow |
| A remote template changes or becomes unavailable | Output can drift or generation can fail outside the codebase | Use a local file or a pinned URL |
| A strict server adapter handles binding, middleware, or errors differently from the selected framework contract | Generated handlers can behave differently across server runtimes | Compare each framework adapter's request, middleware, response, and error paths |
| A strict response template changes body or flush behavior for one framework only | Generated handlers can differ across server runtimes | Compare the standard HTTP and framework-specific response visitors |
| A struct-tag template uses an unknown field | Configuration validation rejects the tag rule | Use only the documented StructTagInfo values |
| A type mapping names a type without a matching local declaration or import | The generated Go package does not compile | Keep the type declaration and import decision together |
additional-initialisms is set without the matching name normalizer | Configuration validation fails | Use ToCamelCaseWithInitialisms or remove the initialisms |
| A content-type short name is not a valid identifier fragment | Configuration validation fails | Use a short name made from letters and digits that starts with a letter |
| Two content-type patterns match one media type under different short names | Generation cannot choose one generated type-name suffix | Make content-type patterns mutually exclusive |
| A custom response media type cannot be deserialized by the client | The generated response exposes the raw body instead of a typed field | Provide a supported deserialization path or consume the raw body |
| A streaming content-type pattern is invalid | Configuration validation fails before generation | Compile and check each regular expression |
| A streaming response writer does not support flushing | The response uses buffered copying instead of immediate chunks | Use a runtime that supports flushing when immediate delivery is required |
An external $ref has no matching import mapping | The referenced Go type cannot be resolved | Match the mapping key to the exact external document path |
An import-mapping key is a JSON pointer | Configuration validation rejects the mapping | Map the path or URL of the external $ref document instead |
| A standard HTTP file is built with an unsupported Go version | The file is excluded or the generated API cannot work as expected | Use Go 1.22 or newer for standard HTTP output |
| A model and operation configuration disagree about named anonymous types | One generated section can reference declarations that no section emits | Keep the relevant output options consistent across configurations |
Key files
| File | Why to read it |
|---|---|
| pkg/…/codegen.go | Shows the generation lifecycle: configuration state, template loading, type and import collection, rendering, and final formatting |
| pkg/…/configuration.go | Defines the public configuration model and the output-option contracts for templates, tags, mappings, names, media types, warnings, and validation |
| pkg/…/structtags.go | Defines the field values available to struct-tag templates and the merge rules for default and custom tags |
| pkg/…/typemapping.go | Defines default primitive and format mappings and the merge and resolution behavior for user overrides |
| pkg/…/schema.go | Shows how schema controls become Go fields, types, omission values, and per-field tag overrides |
| pkg/…/operations.go | Shows how parameter fields use struct tags and how parameter-level controls relate to schema-level controls |
pkg/codegen/templates/imports.tmpl | Illustrates how package, framework, external, and additional imports enter the generated package, including the standard HTTP version guard |
pkg/codegen/templates/typedef.tmpl | Illustrates the small template boundary that turns prepared type data into Go declarations |
pkg/codegen/templates/client-with-responses.tmpl | Provides a concrete user-template override target for response-aware client code |
pkg/codegen/templates/strict/strict-interface.tmpl | Shows the standard HTTP strict response contract, including status, headers, body encoding, and streaming behavior |
pkg/codegen/templates/strict/strict-fiber-interface.tmpl | Shows how the strict response contract maps to Fiber response handling |
pkg/codegen/templates/strict/strict-iris-interface.tmpl | Shows how the strict response contract maps to Iris response handling |
pkg/codegen/templates/strict/strict-http.tmpl | Shows how the standard HTTP strict adapter binds requests, applies middleware, invokes the server interface, and handles errors |
pkg/codegen/templates/strict/strict-echo.tmpl | Shows how the Echo strict adapter maps the shared operation flow to Echo request and response handling |
pkg/codegen/templates/strict/strict-fiber.tmpl | Shows how the Fiber strict adapter maps the shared operation flow to Fiber request and response handling |
pkg/codegen/templates/strict/strict-gin.tmpl | Shows how the Gin strict adapter maps the shared operation flow to Gin request and error handling |
pkg/codegen/templates/strict/strict-iris.tmpl | Shows how the Iris strict adapter maps the shared operation flow to Iris request and error handling |
pkg/codegen/templates/strict/strict-responses.tmpl | Shows shared response type shapes for status-independent generated responses |
| examples/…/config.yaml | Demonstrates a focused type-mapping policy without restating the built-in mappings |
| docs/configuration.md | Gives the configuration reference and the complete set of output-option names |