x-go-type and x-go-type-import¶
Override the generated type definition (and optionally, add an import from another package).
Overview¶
Using the x-go-type (and optionally, x-go-type-import when you need to import another package) allows overriding the type that oapi-codegen determined the generated type should be.
Example¶
openapi: "3.0.0"
info:
version: 1.0.0
title: x-go-type
components:
schemas:
Client:
type: object
required:
- name
properties:
name:
type: string
id:
type: number
ClientWithExtension:
type: object
required:
- name
properties:
name:
type: string
# this is a bit of a contrived example, as you could instead use
# `format: uuid` but it explains how you'd do this when there may be
# a clash, for instance if you already had a `uuid` package that was
# being imported, or ...
x-go-type: googleuuid.UUID
x-go-type-import:
path: github.com/google/uuid
name: googleuuid
id:
type: number
# ... this is also a bit of a contrived example, as you could use
# `type: integer` but in the case that you know better than what
# oapi-codegen is generating, like so:
x-go-type: int64
Generated Code¶
From here, we now get two different models:
type Client struct {
Name string `json:"name" validate:"required"`
ID *float32 `json:"id,omitempty"`
}
type ClientWithExtension struct {
Name googleuuid.UUID `json:"name" validate:"required"`
ID *int64 `json:"id,omitempty"`
}
Imports follow the types¶
A package is imported only when a generated type refers to it. format: uuid generates uuid.UUID from github.com/google/uuid, so overriding every uuid schema, for example with an overlay, drops that import and lets you point at another package such as the standard library one:
x-go-type: uuid.UUID
x-go-type-import:
path: uuid
Two things follow from this:
- An
x-go-typethat refers to a package needs itsx-go-type-import.x-go-type: uuid.UUIDalone only getsgithub.com/google/uuidwhile some other schema still generatesuuid.UUID. Without that, goimports adds the standard libraryuuidinstead. That builds on Go 1.27, with the standard library type rather thangoogle/uuid, and fails on older Go withpackage uuid is not in std. The generator logs a warning that lists the schemas:
WARN x-go-type: package uuid is only imported when a type uses github.com/google/uuid, so a schema that names it without an x-go-type-import may not build schemas=GetThings.Response.id hint="set x-go-type-import to the package you want, e.g. {path: github.com/google/uuid}"
uuid. Give the override an alias, x-go-type: stduuid.UUID with name: stduuid next to path: uuid under x-go-type-import.
Full Example¶
You can see this in more detail in the example code.
Related Extensions¶
x-go-name- Override the generated name of a field or typex-go-type-name- Override the generated name of a type only