fizz

package module
v0.0.0-...-047b823 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Fizz

Gin Fizz

Fizz is a wrapper for Gin based on gadgeto/tonic.

It generates wrapping gin-compatible handlers that do all the repetitive work and wrap the call to your handlers. It can also generate an almost complete OpenAPI 3.2.1 specification of your API.



Fizz v0.30 requires Go 1.27 or later and emits OpenAPI 3.2.1 only. If you are coming from v0.23 or earlier, read MIGRATION.md: the generated document changed.

Getting started

To create a Fizz instance, you can pass an existing Gin engine to fizz.NewFromEngine, or use fizz.New that will use a new default Gin engine.

engine := gin.Default()
engine.Use(...) // register global middlewares

f := fizz.NewFromEngine(engine)

A Fizz instance implements the http.HandlerFunc interface, which means it can be used as the base handler of your HTTP server.

srv := &http.Server{
   Addr:    ":4242",
   Handler: f,
}
srv.ListenAndServe()

Options

Both constructors accept options. This example reads the descriptions from a doc tag and documents pointers as plain (non-null) types.

f := fizz.New(
	fizz.WithTagNames(openapi.TagNames{Description: "doc"}),
	fizz.WithPointersAreNullable(false),
)
f.GET("/pets", []fizz.OperationOption{fizz.ID("listPets")},
	tonic.Handler(func(*gin.Context, *optionsIn) error { return nil }, 200))

op := f.Generator().API().Paths["/pets"].GET
b, err := json.Marshal(op.Parameters[0])
if err != nil {
	panic(err)
}
fmt.Println(string(b))
option effect
WithTagNames(openapi.TagNames) Rename the struct tags that fizz owns. See Tags.
WithSchemaNamer(func(reflect.Type) string) Name the component schema of a type. See Naming.
WithRequestBodyNamer(func(opID string, t reflect.Type) string) Name the component schema of a request body.
WithOperationIDNamer(func(method, path, handlerName string) string) Derive the ID of an operation registered without fizz.ID.
WithPointersAreNullable(bool) Whether a pointer also accepts null. Default true.
WithAnnotationStyle(openapi.AnnotationStyle) How annotations are attached to a $ref: openapi.SiblingAnnotations (default) or openapi.AllOfWrap.
WithDefaultMediaType(string) The media type of bodies. Default tonic.MediaType().
WithHooks(openapi.Hooks) Adjust the generated document. See Hooks.
WithoutBindHook() Do not install the bind hook. See deepObject.

Handlers

Fizz abstracts the GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD and TRACE methods of a Gin engine. These functions accept a variadic list of handlers as the last parameter, but since Fizz relies on tonic to retrieve the informations required to generate the OpenAPI specification of the operation, only one of the handlers registered MUST be wrapped with Tonic. If several are, the error is recorded (see Errors), the route is still served and the operation is not documented.

In the following example, the BarHandler is a simple middleware that will be executed before the FooHandler, but the generator will use the input/output type of the FooHandler to generate the specification of the operation.

func BarHandler(c *gin.Context) { ... }
func FooHandler(*gin.Context, *Foo) (*Bar, error) { ... }

f := fizz.New()
f.GET("/foo/bar", nil, BarHandler, tonic.Handler(FooHandler, 200))

However, registering only standard handlers that follow the gin.HandlerFunc signature is accepted, but the OpenAPI generator will ignore the operation and it won't appear in the specification.

Operation informations

To enrich an operation, you can pass a list of optional OperationOption functions as the second parameters of the GET, POST, PUT, PATCH, DELETE, OPTIONS and HEAD methods.

// Set the default response description.
// A default status text will be created from the code if it is omitted.
fizz.StatusDescription(desc string)

// Set the summary of the operation.
fizz.Summary(summary string)
fizz.Summaryf(format string, a ...any)

// Set the description of the operation.
fizz.Description(desc string)
fizz.Descriptionf(format string, a ...any)

// Override the ID of the operation.
// Must be a unique string used to identify the operation among
// all operations described in the API.
fizz.ID(id string)

// Mark the operation as deprecated.
fizz.Deprecated(deprecated bool)

// Add an additional response to the operation.
// The example argument will populate a single example in the response schema.
// For populating multiple examples, use fizz.ResponseWithExamples.
// Notice that example and examples fields are mutually exclusive.
// model, header, and example may be `nil`.
fizz.Response(statusCode, desc string, model any, headers []*ResponseHeader, example any)

// ResponseWithExamples is a variant of Response that supports providing multiple examples.
// Examples argument will populate multiple examples in the response schema.
// For populating a single example, use fizz.Response.
// Notice that example and examples fields are mutually exclusive.
// model, header, and examples may be `nil`.
fizz.ResponseWithExamples(statusCode, desc string, model any, headers []*ResponseHeader, examples map[string]any)

// ResponseWith adds a response built from options: WithModel, WithHeaders,
// WithExample, WithExamples, WithContent (an additional media type) and
// WithResponseExtension.
fizz.ResponseWith(code, desc string, opts ...ResponseOption)

// Add examples to the default response.
fizz.DefaultResponseExamples(examples map[string]any)

// Add an additional header to the default response.
// Model can be of any type, and may also be `nil`,
// in which case the string type will be used as default.
fizz.Header(name, desc string, model any)

// Override the binding model of the operation.
fizz.InputModel(model any)

// Describe the request body: its description, whether it is required and,
// optionally, its media types. Contents replace the inferred one.
fizz.RequestBody(desc string, required bool, contents ...ContentOption)
fizz.Content(mediaType string, model any, encs ...EncodingOption)
fizz.Encoding(property, contentType string)

// Add a parameter, or merge it into the inferred one that has the same
// name and location.
fizz.Parameter(p *openapi.Parameter)

// Add tags to the operation, after the tag of its group.
fizz.Tags(tags ...string)

// Set the external documentation of the operation.
fizz.ExternalDocs(url, desc string)

// Set an "x-" extension of the operation.
fizz.Extension(key string, value any)

// Edit the finished operation. Runs after every other option.
fizz.CustomizeOperation(fn func(*openapi.Operation) error)

// Overrides the top-level security requirement of an operation.
// Note that this function can be used more than once to add several requirements.
fizz.Security(security *openapi.SecurityRequirement)

// Add an empty security requirement to this operation to make other security requirements optional.
fizz.WithOptionalSecurity()

// Remove any top-level security requirements for this operation.
fizz.WithoutSecurity()

// Add a Code Sample to the operation.
fizz.XCodeSample(codeSample *XCodeSample)

// Mark the operation as internal. The x-internal flag is interpreted by third-party tools and it only impacts the visual documentation rendering.
fizz.XInternal()

NOTES:

  • fizz.InputModel allows to override the operation input regardless of how the handler implementation really binds the request parameters. It is the developer responsibility to ensure that the binding matches the OpenAPI specification. The deepObject and cookie parameters are not bound if the model differs from the handler input.
  • The first argument of the fizz.Response method which represents an HTTP status code is of type string because the spec accept the value default. See the Responses Object documentation for more informations.
  • An option that cannot be applied (a duplicate media type, a parameter without a name, an invalid extension key, a failing CustomizeOperation...) is recorded in Errors; the operation is still documented, without what failed.

To describe the request body yourself, for instance a body in XML instead of the JSON one that is inferred from the input:

f := fizz.New()
f.POST("/pets", []fizz.OperationOption{
	fizz.ID("createPet"),
	fizz.RequestBody("The pet to create", true,
		fizz.Content("application/xml", exPet{})),
}, tonic.Handler(func(*gin.Context, *exPet) error { return nil }, 201))

doc, err := f.Document()
if err != nil {
	panic(err)
}
b, err := json.Marshal(doc.Paths["/pets"].POST.RequestBody)
if err != nil {
	panic(err)
}
fmt.Println(string(b))

CustomizeOperation edits the operation once every other option has been applied, whatever the position of the option:

f := fizz.New()
f.GET("/pets", []fizz.OperationOption{
	fizz.CustomizeOperation(func(op *openapi.Operation) error {
		op.Summary += " (beta)"
		return nil
	}),
	fizz.ID("listPets"),
	fizz.Summary("List pets"),
}, tonic.Handler(func(*gin.Context, *optionsIn) error { return nil }, 200))

doc, err := f.Document()
if err != nil {
	panic(err)
}
fmt.Println(doc.Paths["/pets"].GET.Summary)

To help you declare additional headers, predefined variables for Go primitives types that you can use as the third argument of the fizz.Header method are available:

var (
   Integer  int32
   Long     int64
   Float    float32
   Double   float64
   String   string
   Byte     []byte
   Binary   []byte
   Boolean  bool
   DateTime time.Time
)

Groups

Exactly like you would do with Gin, you can create a group of routes using the method Group. Unlike Gin own method, Fizz's one takes two other optional arguments, name and description. These parameters will be used to create a tag in the OpenAPI specification that will be applied to all the routes added to the group.

grp := f.Group("/subpath", "MyGroup", "Group description", middlewares...)

If the name parameter is empty, the tag won't be created and it won't be used.

Subgroups of subgroups can be created to an infinite depth, according yo your needs.

foo := f.Group("/foo", "Foo", "Foo group")

// all routes registered on group bar will have
// a relative path starting with /foo/bar
bar := f.Group("/bar", "Bar", "Bar group")

// /foo/bar/{barID}
bar.GET("/:barID", nil, tonic.Handler(MyBarHandler, 200))

The Use method can be used with groups to register middlewares after their creation.

grp.Use(middleware1, middleware2, ...)

If a group describes a tag that already exists with a different description, the first description is kept and a warning is recorded. To set a tag, with its summary, kind or parent, use f.Generator().SetTag.

Tonic

The subpackage tonic handles path/query/header/body parameters binding in a single consolidated input object which allows you to remove all the boilerplate code that retrieves and tests the presence of various parameters. The OpenAPI generator make use of the input/output types informations of a tonic-wrapped handler reported by tonic to document the operation in the specification.

The handlers wrapped with tonic must follow the following signature.

func(*gin.Context, [input object ptr]) ([output object], error)

Input and output objects are both optional, as such, the minimal accepted signature is:

func(*gin.Context) error

To wrap a handler with tonic, use the tonic.Handler method. It takes a function that follow the above signature and a default status code and return a gin.HandlerFunc function that can be used when you register a route with Fizz of Gin.

Output objects can be of any type, and will be marshalled to the desired media type. Note that the input object MUST always be a pointer to a struct, or the tonic wrapping will panic at runtime.

Operation IDs

Unless you set one with fizz.ID, the ID of an operation comes from the name of its handler: the function name without the import path, the -fm suffix of a method value and the generic arguments. A closure takes the name of the function that encloses it. If that ID is already used, fizz tries pkg.Name, then the method and path (get_users_id). An ID set with fizz.ID is never changed, and one that is already used is an error. Use fizz.WithOperationIDNamer to choose the default yourself.

func MyHandler() gin.HandlerFunc {
   return tonic.Handler(func(c *gin.Context) error {}, 200)
}

f.GET("/foo", []fizz.OperationOption{
   fizz.ID("MyOperationID"),
}, MyHandler())

Location tags

tonic uses three struct tags to recognize the parameters it should bind to the input object of your tonic-wrapped handlers:

  • path: bind from the request path
  • query: bind from the request query string
  • header: bind from the request headers

Fizz binds a fourth location, cookie, and a style:"deepObject" form of query, see below.

The fields that doesn't use one of these tags will be considered as part of the request body.

The value of each struct tag represents the name of the field in each location, with options.

type MyHandlerParams struct {
   ID  int64     `path:"id"`
   Foo string    `query:"foo"`
   Bar time.Time `header:"x-foo-bar"`
}

tonic will automatically convert the value extracted from the location described by the tag to the appropriate type before binding.

NOTE: A path parameter is always required and will appear required in the spec regardless of the validate tag content. A path parameter that is in the route but not in the input type (a handler with no input, for instance) is documented as a required string, with a warning. A gin catch-all /*name is documented as /{name}, and the description of the parameter says that the value may contain a slash.

Tags

Two kinds of struct tags drive the specification. The binder tags are read by tonic, or by fizz on its behalf, and their names are fixed: they are openapi.BinderTags. The fizz tags only enrich the specification, and each can be renamed with fizz.WithTagNames(openapi.TagNames{...}): a zero field keeps the default name, and "-" disables the tag.

tag default name renameable / fixed effect
Description description TagNames.Description Description of the field or parameter.
Example example TagNames.Example Example value, converted to the type of the field. Custom types provide it with Exampler.
Format format TagNames.Format Override the format of the field.
Deprecated deprecated TagNames.Deprecated Mark the field deprecated. Accepts what strconv.ParseBool does; an invalid value is false.
Title title TagNames.Title Title of the schema.
Pattern pattern TagNames.Pattern Regular expression of a string. An invalid expression is recorded and dropped.
ReadOnly readOnly TagNames.ReadOnly Mark the field read-only. Together with writeOnly, both are dropped with a warning.
WriteOnly writeOnly TagNames.WriteOnly Mark the field write-only.
Nullable nullable TagNames.Nullable true makes the field accept null, false removes it, whatever the pointer rule gives.
MultipleOf multipleOf TagNames.MultipleOf The value must be a multiple of this positive number.
AdditionalProperties additionalProperties TagNames.AdditionalProperties Only false is supported: the object accepts no other property. On a $ref it emits unevaluatedProperties: false.
Inline inline TagNames.Inline Emit the schema of a struct field in place of its $ref.
Style style TagNames.Style Serialization style of a parameter, checked per location: query form, spaceDelimited, pipeDelimited, deepObject; header simple; path simple, label, matrix; cookie form, cookie.
AllowReserved allowReserved TagNames.AllowReserved Let a query parameter hold reserved characters unescaped. Query parameters only.
Cookie cookie TagNames.Cookie Bind the field from a cookie. See Cookies.
path path fixed (binder tag) Bind from the path. Always required.
query query fixed (binder tag) Bind from the query string. Options: ,required, ,default=.
header header fixed (binder tag) Bind from a header. Same options as query.
enum enum fixed (binder tag) Comma separated list of the accepted values. Wins over the Enumer of the type at this field.
default default fixed (binder tag) Value bound when none is passed. On a parameter, required is dropped from the spec with a warning. On a body field tonic never applies it, so required is kept, default is dropped and a warning is recorded. A time.Duration default on a parameter is an integer of nanoseconds.
validate validate fixed (binder tag) validator.v9 rules. See Schema validation.
explode explode fixed (binder tag) Whether a query array is exploded (1, t, T, TRUE, true, True, 0, f, F, FALSE).

Tags are use-site annotations: they never change the component schema of a type that is shared by several fields. On a $ref they are emitted as siblings of the $ref, or inside an allOf with fizz.WithAnnotationStyle(openapi.AllOfWrap).

f := fizz.New(fizz.WithSchemaNamer(func(t reflect.Type) string { return t.Name() }))
f.GET("/pets/best", []fizz.OperationOption{fizz.ID("bestPet")},
	tonic.Handler(func(*gin.Context) (*Tagged, error) { return nil, nil }, 200))

b, err := json.Marshal(f.Generator().API().Components.Schemas["Tagged"].Properties)
if err != nil {
	panic(err)
}
fmt.Println(string(b))

JSON/XML

The JSON/XML encoders usually omit a field that has the tag "-". This behaviour is reproduced by the OpenAPI generator ; a field with this tag won't appear in the properties of the schema. The fields are selected as encoding/json does: embedding, dominance, ,string and tag names are followed.

In the following example, the field Input is used only for binding request body parameters and won't appear in the output encoding while Output will be marshaled but will not be used for parameters binding.

type Model struct {
	Input  string `json:"-"`
	Output string `json:"output" binding:"-"`
}

Request body

If you want to make a request body field mandatory, you can use the tag validate:"required". The validator used by tonic will ensure that the field is present. To be able to make a difference between a missing value and the zero value of a type, use a pointer.

To explicitly ignore a parameter from the request body, use the tag binding:"-".

The request body is documented for every method except GET and HEAD, which have no generally defined semantics for it per RFC 9110. DELETE bodies are documented, because tonic binds them. The body is named after the operation ID (ListPetsInput, see Naming), and requestBody.required is set when one of its fields is required.

Schema validation

The OpenAPI generator recognize some tags of the go-playground/validator.v9 package (the one tonic uses) and translate those to the keywords of the schema that are taken from the JSON Schema definition.

The supported rules are: len, min, max, eq, ne, gt, gte, lt, lte, oneof, email, url, uri, uuid, uuid3, uuid4, uuid5, ipv4, ipv6, hostname, alpha, alphanum, numeric, hexadecimal and unique, with dive and keys/endkeys for the elements of slices and maps. An OR group (a|b) becomes an anyOf when every alternative maps to a keyword.

Based on the type of the field that carry the tag, the fields maximum, minimum, exclusiveMaximum, exclusiveMinimum, minLength, maxLength, minItems, maxItems, minProperties and maxProperties of its JSON Schema will be filled accordingly. A field is required only if its validate tag has a single required rule at the root and no omitempty.

OpenAPI specification

To serve the generated OpenAPI specification in either JSON or YAML format, use the handler returned by the fizz.OpenAPI method. If your server is not Gin, f.SpecHandler("json") returns an http.Handler.

To enrich the specification, you can provide additional informations. Head to the OpenAPI 3.2.1 spec for more informations about the API informations that you can specify, or take a look at the type openapi.Info in the file openapi/spec_root.go.

f := fizz.New()
infos := &openapi.Info{
   Title:       "Fruits Market",
   Description: `This is a sample Fruits market server.`,
   Version:     "1.0.0",
}
f.GET("/openapi.json", nil, f.OpenAPI(infos, "json"))

The document is built once per change of the generator and shared by the requests, so serving it while you register routes is safe.

Errors

NOTE: The generator never panics. Registration problems are recorded instead, and f.Errors() returns them in registration order. A problem is a warning (IsWarning() bool is true, the document is still complete), or an error that concerns one operation. f.Err() joins the errors that are not warnings, or is nil: call it before starting your API.

Errors that concern an operation are wrapped in an *openapi.OperationError{Method, Path, ID, Err}, so use errors.As to reach the *openapi.FieldError, *openapi.TypeError or *openapi.CollisionError inside.

f := fizz.New()
h := tonic.Handler(func(*gin.Context) error { return nil }, 200)
f.GET("/a", []fizz.OperationOption{fizz.ID("same")}, h)
f.GET("/b", []fizz.OperationOption{fizz.ID("same")}, h)

err := f.Err()
fmt.Println(err)
var opErr *openapi.OperationError
if errors.As(err, &opErr) {
	fmt.Println(opErr.Method, opErr.Path)
}

Most problems are limited to a field or a parameter: the operation is kept without it. An operation that cannot be built (a duplicate fizz.ID, an input that is not a struct, a response code used twice) is left out of the document, and the route is still served. Nothing a failed operation created remains in the document.

Servers information

If the OpenAPI specification refers to an API that is not hosted on the same domain, or using a path prefix not included in the spec, you will have to declare server information. This can be achieved using the f.Generator().SetServers method.

f := fizz.New()
f.Generator().SetServers([]*openapi.Server{
   {
      Description: "Fruits Market - production",
      URL:         "https://example.org/api/1.0",
   },
})

Security schemes

If your API requires authentication, you have to declare the security schemes that can be used by the operations. This can be achieved using the f.Generator().SetSecuritySchemes method.

f := fizz.New()
f.Generator().SetSecuritySchemes(map[string]*openapi.SecuritySchemeOrRef{
   "apiToken": {
      Value: &openapi.SecurityScheme{
         Type: "apiKey",
         In:   "header",
         Name: "x-api-token",
      },
   },
})

Once defined, the security schemes will be available for all operations. You can override them on an per-operation basis using the fizz.Security() function.

fizz.Security(&openapi.SecurityRequirement{
   "apiToken": []string{},
})

Components

The output types of your handlers are registered as components within the generated specification. See Naming for how they are named, and Interfaces to control their schema. A component is written once per type; a field that uses it only references it with a $ref.

A pointer to a struct is documented as anyOf: [{$ref}, {type: "null"}], other pointers get "null" in their type. Use fizz.WithPointersAreNullable(false) to document pointers as plain types, or the nullable tag per field.

To add a component yourself, or other parts of the document that fizz does not infer, use the Register* and Set* methods of f.Generator(): RegisterSchema, RegisterType, RegisterParameter, RegisterResponse, RegisterExample, RegisterRequestBody, RegisterHeader, SetTag, SetTagGroups, SetSelf, SetJSONSchemaDialect, SetExternalDocs and SetExtension.

Naming

By default, the name of a component is the package name and the type name in CamelCase, concatenated, without the import path (the main package has no prefix). As such, please ensure that you don't use the same type name in two eponym package in your application: when two types claim a name, the first keeps it, a *openapi.CollisionError is recorded, and the other one is inlined. Whatever the source, a name is sanitized to ^[A-Za-z0-9._-]+$.

The instance of a generic type is named after its type arguments: GenericPage_models.Item, GenericPair_string_int. A slice argument becomes List_T, a map Map_K_V, and a pointer is its element.

The names of the components can be customized, from the highest precedence to the lowest.

  1. Global override, before registering your handlers:
    f := fizz.New()
    f.Generator().OverrideTypeName(reflect.TypeOf(T{}), "OverridedName")
    
  2. Interface: implement the openapi.Typer interface on your types.
    func (*T) TypeName() string { return "OverridedName" }
    
    WARNING: You MUST not rely on the method receiver to return the name, because the method will be called on a new instance created by the generator with the reflect package.
  3. Namer: fizz.WithSchemaNamer takes a function of the type. An empty result selects the default name.

Operation IDs and request bodies have their own namers, fizz.WithOperationIDNamer and fizz.WithRequestBodyNamer (the default body name is the operation ID with its first letter upper-cased, followed by Input):

f := fizz.New(
	fizz.WithOperationIDNamer(func(method, path, handler string) string {
		path = strings.NewReplacer("/", "_", "{", "", "}", "").Replace(path)
		return strings.ToLower(method) + path
	}),
	fizz.WithRequestBodyNamer(func(opID string, _ reflect.Type) string {
		return opID + "_body"
	}),
)
f.POST("/pets/:id", nil,
	tonic.Handler(func(*gin.Context, *namedIn) error { return nil }, 201))

op := f.Generator().API().Paths["/pets/{id}"].POST
fmt.Println(op.ID)
fmt.Println(op.RequestBody.Content["application/json"].Schema.Ref)

Interfaces

The spec generator creates OpenAPI schemas for your types based on their reflection kind. To control the schema of a named type, implement one of these interfaces, on the value or on the pointer receiver. A type that implements any of them is always a component, a named scalar included, and the fields that use it reference it.

interface method effect
openapi.SchemaProvider OpenAPISchema() *openapi.Schema Replaces the reflected schema. The type is not inspected.
openapi.Enumer Enum() []any Sets the enum of the component, converted to the kind of the type.
openapi.SchemaCustomizer CustomizeSchema(*openapi.Schema) error Edits the schema once it is built. On an error the schema keeps its previous state.

They run in this order, once per type: reflection or SchemaProvider, then Enumer, then SchemaCustomizer, then the SchemaHook. A field tag still wins at the use site: a field enum tag overrides the Enumer of its type for that field, and the component is not touched.

The types of the example below implement Enumer and SchemaProvider:

type Status string

func (Status) Enum() []any { return []any{"active", "archived"} }

type Money struct{ Cents int64 }

func (Money) OpenAPISchema() *openapi.Schema {
	return &openapi.Schema{Type: openapi.Types("string"), Pattern: `^\d+\.\d{2}$`}
}

type Account struct {
	Status  Status `json:"status"`
	Balance Money  `json:"balance"`
}
f := fizz.New(fizz.WithSchemaNamer(func(t reflect.Type) string { return t.Name() }))
f.GET("/accounts", []fizz.OperationOption{fizz.ID("listAccounts")},
	tonic.Handler(func(*gin.Context) ([]Account, error) { return nil, nil }, 200))

schemas := f.Generator().API().Components.Schemas
for _, name := range []string{"Status", "Money"} {
	b, err := json.Marshal(schemas[name])
	if err != nil {
		panic(err)
	}
	fmt.Println(name, string(b))
}

Older, simpler hooks still work. Implement openapi.DataType (Type() string and Format() string) to give a type a type and a format, or call OverrideDataType for the highest precedence. Implement openapi.Nullable to choose whether a type is nullable.

type NullString sql.NullString

func (NullString) Nullable() bool { return true }

f.Generator().OverrideDataType(reflect.TypeOf(&UUIDv4{}), "string", "uuid")

WARNING: You MUST not rely on the method receivers to return the type and format, because these methods will be called on a new instance created by the generator with the reflect package.

Native and imported types support

Fizz supports some native and imported types. A schema with a proper type and format will be generated automatically, removing the need for creating your own custom schema.

  • time.Time: a date-time string.

  • time.Duration: an int64, in nanoseconds. A body field default such as "1s" is emitted as nanoseconds.

  • url.URL: an object, as encoding/json encodes it. Use OverrideDataType (f.Generator().OverrideDataType(reflect.TypeFor[url.URL](), "string", "uri")) to document it as a string.

  • net.IP, netip.Addr and netip.Prefix: a string with the format ip.

    Note that, according to the doc, the inherent version of the address is a semantic property, and thus cannot be determined by Fizz. Therefore, the format returned is simply ip. If you want to specify the version, you can use the tags format:"ipv4" or format:"ipv6".

  • uuid.UUID, from the standard library, from gofrs/uuid and from google/uuid: a uuid string.

  • []byte: a string with contentEncoding: base64. json.RawMessage is the empty schema.

  • big.Int is an integer, big.Float and big.Rat are strings.

A type that implements encoding.TextMarshaler is a string. One that only implements json.Marshaler keeps the schema of its kind, and a warning points to SchemaProvider.

Markdown

Throughout the specification description fields are noted as supporting CommonMark markdown formatting. Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by CommonMark 0.27. Tooling MAY choose to ignore some CommonMark features to address security concerns. source

To help you write markdown descriptions in Go, a simple builder is available in the sub-package markdown. This is quite handy to avoid conflicts with backticks that are both used in Go for litteral multi-lines strings and code blocks in markdown.

Providing Examples for Custom Types

To be able to provide examples for custom types, they must implement json.Marshaler and the following interface:

type Exampler interface {
       ParseExample(v string) (any, error)
}

If the custom type implements the interface, Fizz will pass the value from the example tag to the ParseExample method and use the return value as the example in the OpenAPI specification. An example must be encodable as JSON: one that is not (NaN, a channel) is recorded in Errors() and dropped. A yaml.Marshaler is ignored, because the YAML document is derived from the JSON one.

Hooks

Hooks adjust what fizz generates when a tag or an interface is not enough. Pass them with fizz.WithHooks(openapi.Hooks{...}); calls compose in order. Any member may be nil.

hook signature when
Schema func(*openapi.SchemaContext, *openapi.Schema) Once per component written from a Go type.
Field func(*openapi.FieldContext, *openapi.Schema) (skip bool) Per body property, after its tags. true leaves it out. Not called for parameters.
Parameter func(*openapi.ParameterContext, *openapi.Parameter) (skip bool) Per parameter, after its tags. true leaves it out, except a path parameter, which is kept with a warning.
Operation func(*openapi.OperationContext, *openapi.Operation) error Per operation, last. It gets a copy; on an error the changes are discarded and the error is recorded. It cannot change the ID.
Document func(*openapi.OpenAPI) error Per document, on a deep copy, when it is served or returned by f.Document().

The order in which everything applies is the precedence of the generator:

  1. Component stage, once per named type, written once into components/schemas: reflection (or SchemaProvider, which replaces it), then Enumer and SchemaCustomizer, then SchemaHook.
  2. Use-site stage, per field, parameter or operation, and never mutating a component: struct tags, then FieldHook and ParameterHook, then the operation options (fizz.CustomizeOperation runs last of them), then OperationHook. A field tag wins over a type interface here.
  3. Document stage: DocumentHook, on a deep copy, once per generation of the document.

DocumentHook applies only to the served output (f.SpecHandler, f.OpenAPI) and to f.Document(). It never runs for f.Generator().API(), which returns a deep copy of the unhooked document. If the hook fails, the document is unavailable: the handler answers 500 and the error is recorded once per generation.

The other hooks run while the generator is locked: they must not call methods of the Generator, and a panic is not recovered. They affect what is generated after they are set, so pass them to fizz.New before you register routes.

This example adds an x-tagGroups extension to the served document. The hook edits a copy, so Generator().API() is unchanged:

f := fizz.New(fizz.WithHooks(openapi.Hooks{
	Document: func(doc *openapi.OpenAPI) error {
		doc.XTagGroups = append(doc.XTagGroups, &openapi.XTagGroup{
			Name: "Pets",
			Tags: []string{"pets"},
		})
		return nil
	},
}))
f.GET("/pets", []fizz.OperationOption{fizz.ID("listPets")},
	tonic.Handler(func(*gin.Context, *optionsIn) error { return nil }, 200))

doc, err := f.Document()
if err != nil {
	panic(err)
}
b, err := json.Marshal(doc.XTagGroups)
if err != nil {
	panic(err)
}
fmt.Println(string(b))

deepObject query parameters

A query parameter can use the OpenAPI deepObject style, ?filter[color]=red&filter[size]=m. Tag a map or a struct field:

type ListPetsInput struct {
	Filter map[string]string `query:"filter" style:"deepObject"`
}

The parameter is documented with style: deepObject, explode: true and an inline object schema, which is never nullable. The type of the field is a map[string]S, a struct, or a pointer to either, where S is a scalar (a string, a bool, an integer, a float, or a type that implements encoding.TextUnmarshaler) or a slice of scalars. A struct member is named after its json tag, matched exactly; one with json:"-", or unexported, is skipped.

Nesting policy, enforced when binding:

  • One level only. filter[a][b]=x is an error (bind.ErrNestedKey), and the request is answered 400.
  • The values are scalars or slices of scalars. A slice is filled by repeating the key, filter[tag]=a&filter[tag]=b; a scalar key repeated, an unclosed or empty bracket, or a value that does not convert is a 400.
  • A parameter whose keys are all absent stays nil.
  • A deepObject parameter is required only with validate:"required" on the field. The ,required option and a default value are generation errors, because tonic would bind them. explode:"false" is undefined for deepObject: it is a warning and explode stays true. A struct member with validate:"required" is listed in the required of the schema.

tonic knows nothing of deepObject, so fizz binds it through a global bind hook:

  • fizz.New and fizz.NewFromEngine install it by calling fizz.InstallBindHook(). It wraps the current tonic bind hook, which is process-global: it is idempotent and safe for concurrent use, a hook that was set before New is kept, and it only acts on routes registered with fizz.
  • fizz.WithoutBindHook() opts out. The parameters are still documented but not bound, unless you install the hook yourself. It does not remove a hook that an earlier New installed.
  • A hook that you set after New replaces fizz's. Compose it with tonic.SetBindHook(fizz.BindHook(next)), or call fizz.InstallBindHook() again. A request that reaches a route whose hook was replaced logs a warning in gin debug mode.
f := fizz.New()
f.GET("/pets", []fizz.OperationOption{fizz.ID("listPets")},
	tonic.Handler(func(c *gin.Context, in *deepObjectIn) error {
		fmt.Println(in.Filter)
		return nil
	}, 204))

req := httptest.NewRequest("GET", "/pets?filter[color]=red", nil)
f.ServeHTTP(httptest.NewRecorder(), req)

Cookies

A field with a cookie tag is documented as an in: cookie parameter and bound from the request cookies. Only scalar fields (or pointers to scalars) are cookies; a struct, a slice or a map is a recorded error and the field is skipped. The tag is read by the same bind hook as deepObject, so it follows the same installation rules.

  • Present: the value is converted to the type of the field, from the raw value of the cookie. It is not URL-decoded.
  • Absent, with a default (the ,default= option of the cookie tag, or the default tag): the field takes the default. When both are set, the option wins, as in tonic. A default that does not convert to the type of the field is a binding error.
  • Present but empty: the field gets the empty value ("" for a string). The default is not applied.
  • Absent, with the ,required option and no default: a binding error that names the cookie (400 by default).
  • Absent, without a default and not required: the field is left alone.

The cookie:"lang,default=en" and cookie:"t,required" options are documented in the spec and bound at runtime, as tonic does for the options of query and header. A default makes the cookie optional in the spec, so required is dropped with a warning when both are set. Like tonic, which treats an empty query or header value as missing, ,required is not satisfied by an empty cookie (unless a default is set). validate:"required" still works, and is checked by tonic after the binding.

f := fizz.New()
f.GET("/me", []fizz.OperationOption{fizz.ID("getMe")},
	tonic.Handler(func(c *gin.Context, in *cookieIn) error {
		fmt.Printf("session=%s lang=%s\n", in.Session, in.Lang)
		return nil
	}, 204))

req := httptest.NewRequest("GET", "/me", nil)
req.AddCookie(&http.Cookie{Name: "session", Value: "abc"})
f.ServeHTTP(httptest.NewRecorder(), req)

Docs UI

f.Docs(path, specURL string, ui ...fizz.DocsUI) registers a GET route that serves an interactive page for the document served at specURL. The route is not part of the specification.

  • Swagger UI is the default: f.Docs("/docs", "/openapi.json").
  • fizz.ScalarUI() selects Scalar, fizz.SwaggerUI() selects Swagger UI explicitly. Both accept docsui options (WithTitle, WithUIConfig, WithCSPNonce, WithAssetURLs).
  • fizz.EmbeddedSwaggerUI() and fizz.EmbeddedScalarUI() serve the assets from your binary at <path>/assets/, instead of from jsDelivr, so the page makes no request to a third-party host. Only a program that calls one of them carries the assets.
  • The choice is always honored: fizz never falls back to another UI. Giving more than one is a mistake: it is recorded in Errors() and the first is used.
  • The CDN pages pin the assets (Swagger UI 5.34.1 and Scalar 1.76.4, see docs/compat.md) with Subresource Integrity, set crossorigin and a no-referrer policy, and force Swagger UI's validatorUrl to null, so the page never sends your document to a validator service.
  • Without Gin, docsui.SwaggerUI(specURL) and docsui.ScalarUI(specURL) return an http.Handler.
f := fizz.New()
f.GET("/openapi.json", nil, f.OpenAPI(&openapi.Info{Title: "Pets", Version: "1.0.0"}, "json"))
f.Docs("/docs", "/openapi.json")                              // Swagger UI, the default
f.Docs("/scalar", "/openapi.json", fizz.ScalarUI())           // Scalar, from a CDN
f.Docs("/offline", "/openapi.json", fizz.EmbeddedSwaggerUI()) // Swagger UI, from the binary

for _, path := range []string{"/docs", "/scalar", "/offline"} {
	w := httptest.NewRecorder()
	f.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
	body := w.Body.String()
	fmt.Println(path, w.Code, strings.Contains(body, "swagger-ui"), strings.Contains(body, "scalar"))
}

Swagger UI and OpenAPI 3.2. These are known upstream gaps, taken from the Swagger UI issue tracker and the P0.6 spike (2026-10-30, a hand-made 3.2.1 document); browser verification of the documents that fizz generates is still pending, so treat them as reported behaviour, not as guarantees:

  • itemSchema, the 3.2 schema of sequential media types, is not rendered (swagger-ui#11065). Fizz does not generate itemSchema; it matters for documents you extend with a hook.
  • The tag summary is not displayed; tag kind and parent are unverified.
  • A $ref in an inline response schema is shown as an anonymous object (Scalar keeps the component name).
  • x- extensions are hidden by default, in both Swagger UI and Scalar.
  • A description next to a $ref was rendered by both UIs in the spike; it is still on the verification checklist for fizz's own documents.

Use fizz.ScalarUI() for fuller 3.2 rendering. The details are in docs/compat.md.

YAML

f.OpenAPI(info, "yaml") and f.SpecHandler("yaml") serve the document as application/yaml. The YAML is derived from the JSON document, so both always have the same content. The model carries no yaml tag, and a MarshalYAML method on a type of yours is ignored, for examples too. Use openapi.MarshalJSON(doc) and openapi.MarshalYAML(doc) to encode a document yourself.

f := fizz.New()
f.GET("/openapi.yaml", nil, f.OpenAPI(&openapi.Info{Title: "Pets", Version: "1.0.0"}, "yaml"))

w := httptest.NewRecorder()
f.ServeHTTP(w, httptest.NewRequest("GET", "/openapi.yaml", nil))
first, _, _ := strings.Cut(w.Body.String(), "\n")
fmt.Println(w.Header().Get("Content-Type"))
fmt.Println(first)

Known limitations

  • Only operations that are wrapped with tonic are documented. A plain gin.HandlerFunc route is served and left out of the specification, as is a route with more than one tonic-wrapped handler (the latter is an error in Errors()).
  • Gin and tonic are the only router and binder. The binder tags are fixed to tonic's. The openapi, bind and docsui packages import neither, and can be used with another router.
  • The request body is not documented for GET and HEAD.
  • The additionalProperties tag only accepts false.
  • Types that JSON cannot encode (channels, functions, complex numbers) are recorded as errors and the field is left out of the schema.
  • Recursive types are supported: a cycle is cut with a $ref, and an embedded cycle follows the field selection of encoding/json. A recursive type cannot be inlined with the inline tag.
  • A default value of a parameter must match what tonic can bind: a time.Duration is an integer of nanoseconds, not "1s".
  • The deepObject style has the nesting policy above, and cookies are scalar only, without a style or explode.
  • Fizz does not infer callbacks, webhooks or links. Add them with the Generator setters, fizz.CustomizeOperation or a hook.

Gaps found by checking the output against the official OpenAPI 3.2 examples (tracked in docs/plan/PLAN-v2.md, Phase 10). They do not make the document invalid; each one is a feature fizz cannot express yet:

  • Webhooks: there is no API to declare them, so the webhooks object is never emitted. Add it with a DocumentHook.
  • Components of kind link, callback and path item cannot be registered, so a $ref to one (set with CustomizeOperation) dangles. Add the component with a DocumentHook.
  • Path-item-level parameters and $ref to a component parameter are not supported: a shared path parameter is repeated in each operation.
  • Examples on a non-default response media type (for example text/html) cannot be set: WithExample and WithExamples only target the default media type.
  • The description of an inline (anonymous) struct body or response cannot be set. Give the type a name and use a SchemaCustomizer, which makes it a component.
  • A request body cannot be a $ref to a component or external document: Operation.RequestBody has no reference form, so neither CustomizeOperation nor a DocumentHook can express it yet.
  • A Schema cannot carry $id or $anchor.
  • The default (tonic) response has no singular example, only examples, and declaring the same status code with Response is a duplicate error.
  • A required body field loses its default tag, with a warning, although OpenAPI allows both.
  • Under tonic, a slice or array header or path parameter is a generation error, and an optional non-string header needs a default tag, otherwise an absent header returns 400 (a warning says so).
  • Swagger UI renders OpenAPI 3.2 only partly, see Docs UI.
  • Tools that read OpenAPI 3.0 only cannot use the generated document as is. See MIGRATION.md for a DocumentHook that rewrites it.

Examples

Every go block of this document that follows an <!-- example: ... --> marker is the body of a runnable Example function of the repository, and a test fails if they differ. The input types they use are declared next to them, in example_test.go and example_readme_test.go.

A simple runnable API is available in examples/market.

go build
./market
# Retrieve the specification marshaled in JSON.
curl -i http://localhost:4242/openapi.json

Conformance testing

Fizz output is checked against the official OAS 3.2.1 JSON Schema and the OpenAPI Initiative's examples and schema fixtures, upgraded to 3.2.1 (attribution in internal/conformance/oai/NOTICE). It is also checked against the examples of the specification text, against reproduction apps built from the official examples, and with spec-driven request tests. A second validator, libopenapi-validator, cross-checks the corpus and the goldens in a separate module.

Credits

Fizz is based on gin-gonic/gin and use gadgeto/tonic. ❤

Documentation

Overview

Example (DeepObject)

This example binds a deepObject query parameter: ?filter[color]=red fills the map. New installs the tonic bind hook that does it.

package main

import (
	"fmt"
	"net/http/httptest"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
)

type deepObjectIn struct {
	Filter map[string]string `query:"filter" style:"deepObject"`
}

func main() {
	f := fizz.New()
	f.GET("/pets", []fizz.OperationOption{fizz.ID("listPets")},
		tonic.Handler(func(c *gin.Context, in *deepObjectIn) error {
			fmt.Println(in.Filter)
			return nil
		}, 204))

	req := httptest.NewRequest("GET", "/pets?filter[color]=red", nil)
	f.ServeHTTP(httptest.NewRecorder(), req)
}
Output:
map[color:red]
Example (Interfaces)

This example gives two types their schema with the Enumer and SchemaProvider interfaces. Both become components that the fields reference.

package main

import (
	"encoding/json"
	"fmt"
	"reflect"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
	"github.com/KeisukeFD/fizz/openapi"
)

// Status lists its valid values: the component gets an enum.
type Status string

func (Status) Enum() []any { return []any{"active", "archived"} }

// Money describes its own schema, instead of the one of its fields.
type Money struct{ Cents int64 }

func (Money) OpenAPISchema() *openapi.Schema {
	return &openapi.Schema{Type: openapi.Types("string"), Pattern: `^\d+\.\d{2}$`}
}

// Account uses both.
type Account struct {
	Status  Status `json:"status"`
	Balance Money  `json:"balance"`
}

func main() {
	f := fizz.New(fizz.WithSchemaNamer(func(t reflect.Type) string { return t.Name() }))
	f.GET("/accounts", []fizz.OperationOption{fizz.ID("listAccounts")},
		tonic.Handler(func(*gin.Context) ([]Account, error) { return nil, nil }, 200))

	schemas := f.Generator().API().Components.Schemas
	for _, name := range []string{"Status", "Money"} {
		b, err := json.Marshal(schemas[name])
		if err != nil {
			panic(err)
		}
		fmt.Println(name, string(b))
	}
}
Output:
Status {"type":"string","enum":["active","archived"]}
Money {"type":"string","pattern":"^\\d+\\.\\d{2}$"}
Example (MigrateAPICopy)

This example shows that Generator().API() returns a copy: change the document with the setters, a hook or an option, not through the copy.

package main

import (
	"fmt"

	"github.com/KeisukeFD/fizz"
	"github.com/KeisukeFD/fizz/openapi"
)

func main() {
	f := fizz.New()
	doc := f.Generator().API()
	doc.Info.Title = "changed through the copy"
	fmt.Printf("%q\n", f.Generator().API().Info.Title)

	f.Generator().SetInfo(&openapi.Info{Title: "Pets", Version: "1.0.0"})
	fmt.Printf("%q\n", f.Generator().API().Info.Title)
}
Output:
""
"Pets"
Example (MigrateBindHook)

This example owns the tonic bind hook. WithoutBindHook keeps New from installing the hook of fizz, and fizz.BindHook(next) puts it back around your hook: the deepObject and cookie parameters bind again.

prev := tonic.GetBindHook()
defer tonic.SetBindHook(prev)

f := fizz.New(fizz.WithoutBindHook())
tonic.SetBindHook(fizz.BindHook(func(c *gin.Context, in any) error {
	return tonic.DefaultBindingHook(c, in)
}))
f.GET("/pets", []fizz.OperationOption{fizz.ID("listPets")},
	tonic.Handler(func(c *gin.Context, in *deepObjectIn) error {
		fmt.Println(in.Filter)
		return nil
	}, 204))

f.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/pets?filter[color]=red", nil))
Output:
map[color:red]
Example (MigrateDeleteBody)

This example documents a DELETE with a body. tonic binds a DELETE body, so fizz documents it; GET and HEAD bodies are still left out.

package main

import (
	"fmt"
	"maps"
	"slices"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
)

type migrateDeleteIn struct {
	ID     int    `path:"id"`
	Reason string `json:"reason" validate:"required"`
}

func main() {
	f := fizz.New()
	f.DELETE("/pets/:id", []fizz.OperationOption{fizz.ID("deletePet")},
		tonic.Handler(func(*gin.Context, *migrateDeleteIn) error { return nil }, 204))

	body := f.Generator().API().Paths["/pets/{id}"].DELETE.RequestBody
	fmt.Println(body != nil, body.Required, slices.Sorted(maps.Keys(body.Content)))
}
Output:
true true [application/json]
Example (MigrateEnumRef)

This example uses a type that implements Enumer as a query parameter. The parameter references the component of the type, where it used to inline a plain string.

f := fizz.New(fizz.WithSchemaNamer(func(t reflect.Type) string { return t.Name() }))
f.GET("/accounts", []fizz.OperationOption{fizz.ID("listAccounts")},
	tonic.Handler(func(*gin.Context, *migrateEnumIn) error { return nil }, 200))

api := f.Generator().API()
b, err := json.Marshal(api.Paths["/accounts"].GET.Parameters[0].Value.Schema)
if err != nil {
	panic(err)
}
fmt.Println(string(b))
Output:
{"$ref":"#/components/schemas/Status"}
Example (MigrateErrors)

This example reads the errors of the generation. Panics are gone: every problem is recorded, an operation's problems are wrapped in an *openapi.OperationError, and errors.As finds what is inside.

package main

import (
	"errors"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
	"github.com/KeisukeFD/fizz/openapi"
)

type migrateBadIn struct {
	Events chan int `json:"events"`
}

func main() {
	f := fizz.New()
	f.POST("/jobs/:id", []fizz.OperationOption{fizz.ID("createJob")},
		tonic.Handler(func(*gin.Context, *migrateBadIn) error { return nil }, 201))

	for _, err := range f.Errors() {
		var op *openapi.OperationError
		var typ *openapi.TypeError
		var warn *openapi.Warning
		switch {
		case errors.As(err, &warn):
			fmt.Println("warning:", warn.Msg)
		case errors.As(err, &typ):
			fmt.Println("error:", typ.Message, typ.Type)
		}
		if errors.As(err, &op) {
			fmt.Println("  operation:", op.Method, op.Path, op.ID)
		}
	}
	fmt.Println(f.Err() != nil)
}
Output:
error: unsupported type chan int
  operation: POST /jobs/{id} createJob
warning: path parameter "id" is declared in the path but missing from the input: synthesized as a required string
true
Example (MigrateModel)

This example builds the schema and the parameters of the OpenAPI model in its v0.30 shape: a TypeSet, json.Number bounds, a pointer Explode, and an OrRef that holds a Value or a Ref.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/KeisukeFD/fizz/openapi"
)

func main() {
	limit := &openapi.ParameterOrRef{Value: &openapi.Parameter{
		Name:    "limit",
		In:      "query",
		Explode: new(true),
		Schema: &openapi.Schema{
			Type:     openapi.Types("integer", "null"), // was Type: "integer", Nullable: true
			Minimum:  openapi.Num(0),                   // was Minimum: 0, an int
			Examples: []any{10},                        // was Example: 10
		},
	}}
	shared := &openapi.ParameterOrRef{Ref: &openapi.Reference{Ref: "#/components/parameters/Page"}}

	fmt.Println(limit.Value.Name, shared.Ref.Ref)
	for _, p := range []*openapi.ParameterOrRef{limit, shared} {
		b, err := json.Marshal(p)
		if err != nil {
			panic(err)
		}
		fmt.Println(string(b))
	}
}
Output:
limit #/components/parameters/Page
{"name":"limit","in":"query","schema":{"type":["integer","null"],"examples":[10],"minimum":0},"explode":true}
{"$ref":"#/components/parameters/Page"}
Example (MigrateOperationFromContext)

This example shows that the operation of a request is a copy: changing it affects neither the specification nor the next call.

package main

import (
	"fmt"
	"net/http/httptest"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
)

func main() {
	f := fizz.New()
	f.GET("/me", []fizz.OperationOption{fizz.ID("getMe"), fizz.Summary("Who am I")},
		tonic.Handler(func(c *gin.Context) error {
			op, err := fizz.OperationFromContext(c)
			if err != nil {
				return err
			}
			op.Summary = "changed"
			again, _ := fizz.OperationFromContext(c)
			fmt.Println(op.ID, again.Summary)
			return nil
		}, 204))

	f.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/me", nil))
	fmt.Println(f.Generator().API().Paths["/me"].GET.Summary)
}
Output:
getMe Who am I
Who am I
Example (MigrateOperationIDs)

This example registers handlers without fizz.ID. The default operation ID is the name of the handler; if it is taken, the package-qualified name is tried, then the method and path.

package main

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
)

func listPets(*gin.Context) error { return nil }

type petAPI struct{}

func (*petAPI) get(*gin.Context) error { return nil }

func main() {
	f := fizz.New()
	api := &petAPI{}
	f.GET("/pets", nil, tonic.Handler(listPets, 200))
	f.GET("/cats", nil, tonic.Handler(listPets, 200))
	f.GET("/dogs", nil, tonic.Handler(listPets, 200))
	f.GET("/pets/:id", nil, tonic.Handler(api.get, 200))

	paths := f.Generator().API().Paths
	for _, p := range []string{"/pets", "/cats", "/dogs", "/pets/{id}"} {
		fmt.Println(p, paths[p].GET.ID)
	}
}
Output:
/pets listPets
/cats fizz_test.listPets
/dogs get_dogs
/pets/{id} get
Example (MigrateRecordedErrors)

This example registers options that cannot all be applied. Each problem is recorded and the operation is still documented.

f := fizz.New()
f.POST("/pets", []fizz.OperationOption{
	fizz.ID("createPet"),
	fizz.RequestBody("The pet", true,
		fizz.Content("application/json", exPet{}),
		fizz.Content("application/json", exPet{})),
	fizz.CustomizeOperation(func(*openapi.Operation) error { return errors.New("not today") }),
}, tonic.Handler(func(*gin.Context, *exPet) error { return nil }, 201))

for _, err := range f.Errors() {
	fmt.Println(err)
}
op := f.Generator().API().Paths["/pets"].POST
fmt.Println(op.ID, slices.Sorted(maps.Keys(op.RequestBody.Content)))
Output:
POST /pets (createPet): RequestBody: media type "application/json" is given more than once: the first is kept
POST /pets (createPet): CustomizeOperation: not today
createPet [application/json]
Example (MigrateTagNames)

This example shows what replaces the binder fields of SpecGenConfig: they are fixed to the names of tonic, and a different value is an error. The names that fizz owns are set with WithTagNames.

package main

import (
	"fmt"

	"github.com/KeisukeFD/fizz"
	"github.com/KeisukeFD/fizz/openapi"
)

func main() {
	_, err := openapi.NewGenerator(&openapi.SpecGenConfig{ValidatorTag: "binding"})
	fmt.Println(err)
	fmt.Println(openapi.BinderTags.Validate, openapi.BinderTags.Query)

	f := fizz.New(fizz.WithTagNames(openapi.TagNames{Description: "doc", Example: "-"}))
	fmt.Println(f.Err())
}
Output:
openapi: SpecGenConfig.ValidatorTag = "binding": binder tags are fixed to "validate"
validate query
<nil>
Example (MigrateTypes)

This example prints the schema of types whose mapping changed: a Duration is an integer of nanoseconds, a url.URL an object (a component), a pointer accepts null, and bytes are base64.

package main

import (
	"encoding/json"
	"fmt"
	"net/url"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
)

type migrateModel struct {
	Wait time.Duration `json:"wait"`
	Home url.URL       `json:"home"`
	Nick *string       `json:"nick"`
	Data []byte        `json:"data"`
}

func main() {
	f := fizz.New()
	f.GET("/model", []fizz.OperationOption{fizz.ID("getModel")},
		tonic.Handler(func(*gin.Context) (*migrateModel, error) { return nil, nil }, 200))

	schemas := f.Generator().API().Components.Schemas
	props := schemas["Fizz_testMigrateModel"].Properties
	for _, name := range []string{"wait", "home", "nick", "data"} {
		b, err := json.Marshal(props[name])
		if err != nil {
			panic(err)
		}
		fmt.Println(name, string(b))
	}
	fmt.Println(schemas["Fizz_testMigrateModel"].Properties["home"].Ref != "")
}
Output:
wait {"type":"integer","format":"int64"}
home {"$ref":"#/components/schemas/UrlURL"}
nick {"type":["string","null"]}
data {"type":"string","contentEncoding":"base64"}
true
Example (MigrateYAML)

This example shows that the YAML document is derived from the JSON one. The MarshalYAML method of a user type is ignored, an example included.

f := fizz.New()
f.GET("/pets", []fizz.OperationOption{
	fizz.ID("listPets"),
	fizz.Response("409", "Conflict", exPet{}, nil, migrateYAMLValue{}),
}, tonic.Handler(listPets, 200))

w := httptest.NewRecorder()
f.SpecHandler("yaml").ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
body := w.Body.String()
fmt.Println(strings.Contains(body, "from json"), strings.Contains(body, "from yaml"))
Output:
true false
Example (Naming)

This example names the operation and its request body component instead of using the defaults.

package main

import (
	"fmt"
	"reflect"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
)

type namedIn struct {
	ID   int    `path:"id"`
	Name string `json:"name"`
}

func main() {
	f := fizz.New(
		fizz.WithOperationIDNamer(func(method, path, handler string) string {
			path = strings.NewReplacer("/", "_", "{", "", "}", "").Replace(path)
			return strings.ToLower(method) + path
		}),
		fizz.WithRequestBodyNamer(func(opID string, _ reflect.Type) string {
			return opID + "_body"
		}),
	)
	f.POST("/pets/:id", nil,
		tonic.Handler(func(*gin.Context, *namedIn) error { return nil }, 201))

	op := f.Generator().API().Paths["/pets/{id}"].POST
	fmt.Println(op.ID)
	fmt.Println(op.RequestBody.Content["application/json"].Schema.Ref)
}
Output:
post_pets_id
#/components/schemas/post_pets_id_body
Example (Tags)

This example reads the tags of a struct: title, pattern, multipleOf and readOnly are fizz tags, min, max, gte and lte are validate rules that become schema keywords.

package main

import (
	"encoding/json"
	"fmt"
	"reflect"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
)

// Tagged shows some of the struct tags that enrich a schema.
type Tagged struct {
	Name  string  `json:"name" title:"Pet name" pattern:"^[a-z]+$" validate:"min=1,max=20"`
	Score float64 `json:"score" multipleOf:"0.5" validate:"gte=0,lte=10"`
	ID    string  `json:"id" readOnly:"true"`
}

func main() {
	f := fizz.New(fizz.WithSchemaNamer(func(t reflect.Type) string { return t.Name() }))
	f.GET("/pets/best", []fizz.OperationOption{fizz.ID("bestPet")},
		tonic.Handler(func(*gin.Context) (*Tagged, error) { return nil, nil }, 200))

	b, err := json.Marshal(f.Generator().API().Components.Schemas["Tagged"].Properties)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))
}
Output:
{"id":{"type":"string","readOnly":true},"name":{"type":"string","title":"Pet name","maxLength":20,"minLength":1,"pattern":"^[a-z]+$"},"score":{"type":"number","format":"double","multipleOf":0.5,"maximum":10,"minimum":0}}
Example (Yaml)

This example serves the specification as YAML. The YAML is derived from the JSON document, so both have the same content.

package main

import (
	"fmt"
	"net/http/httptest"
	"strings"

	"github.com/KeisukeFD/fizz"
	"github.com/KeisukeFD/fizz/openapi"
)

func main() {
	f := fizz.New()
	f.GET("/openapi.yaml", nil, f.OpenAPI(&openapi.Info{Title: "Pets", Version: "1.0.0"}, "yaml"))

	w := httptest.NewRecorder()
	f.ServeHTTP(w, httptest.NewRequest("GET", "/openapi.yaml", nil))
	first, _, _ := strings.Cut(w.Body.String(), "\n")
	fmt.Println(w.Header().Get("Content-Type"))
	fmt.Println(first)
}
Output:
application/yaml
openapi: 3.2.1

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	Integer  int32
	Long     int64
	Float    float32
	Double   float64
	String   string
	Byte     []byte
	Binary   []byte
	Boolean  bool
	DateTime time.Time
)

Primitive type helpers.

Functions

func BindHook

func BindHook(next tonic.BindHook) tonic.BindHook

BindHook returns a tonic bind hook that calls next, then binds what tonic does not understand, or rewrites the request for what tonic reads in another form than the document states (tonic binds after the hook, so the request is what changes): a header that is absent takes the field's default tag (tonic reads it as one empty value and ignores the default), spaceDelimited and pipeDelimited query arrays (split on the delimiter, as one value per element) and label and matrix path parameters (their prefix is stripped; a value without it is a binding error). It binds the deepObject query parameters of the route (those tagged style:"deepObject") and its cookie parameters (scalar fields with a cookie tag). A cookie that is absent takes the field's default (the ",default=" option of the cookie tag, else the default tag); one that is present, even empty, keeps its raw value, which is not URL-decoded. An absent cookie with the ",required" option and no default is a binding error, as is an empty one; validate:"required" is also checked by tonic. If next fails, its error is returned unchanged. A binding error is returned as is: tonic wraps it in a tonic.BindError and passes it to the error hook, which answers 400 by default. A nil next stands for tonic.DefaultBindingHook.

New installs it around the current hook (see InstallBindHook), so calling BindHook yourself is only needed when you set a hook after New:

tonic.SetBindHook(myHook)                // replaces fizz's step: deepObject and cookies stop binding
tonic.SetBindHook(fizz.BindHook(myHook)) // composes with it

The hook does nothing for a request that is not served by a route registered with fizz, and it binds at most once per request, so wrapping it twice only costs a call.

Every hook that BindHook returns is recognized by InstallBindHook.

func DefaultResponseExamples

func DefaultResponseExamples(examples map[string]any) func(*openapi.OperationInfo)

DefaultResponseExamples adds additional examples to the default response.

func Deprecated

func Deprecated(deprecated bool) func(*openapi.OperationInfo)

Deprecated marks the operation as deprecated.

func Description

func Description(desc string) func(*openapi.OperationInfo)

Description adds a description to an operation.

func Descriptionf

func Descriptionf(format string, a ...any) func(*openapi.OperationInfo)

Descriptionf adds a description to an operation according to a format specifier.

func Header(name, desc string, model any) func(*openapi.OperationInfo)

Header adds a header to the operation.

func ID

func ID(id string) func(*openapi.OperationInfo)

ID overrides the operation ID.

func InputModel

func InputModel(model any) func(*openapi.OperationInfo)

InputModel overrides the binding model of the operation.

func InstallBindHook

func InstallBindHook()

InstallBindHook wraps the current tonic bind hook with BindHook, unless the current hook is already one that BindHook returned. It is idempotent, safe for concurrent use, and called by New and NewFromEngine unless WithoutBindHook is passed.

The tonic bind hook is process-global: this changes the hook of every tonic handler of the process, fizz's or not (the hook only acts on routes registered with fizz). A hook set with tonic.SetBindHook after the last New replaces fizz's: compose it with tonic.SetBindHook(fizz.BindHook(hook)) or call InstallBindHook again.

Fizz recognizes its own hook by identity. If you wrap the hook that fizz installed inside a hook of your own and then call New again, fizz cannot see inside your closure and wraps once more. That is harmless: the deepObject parameters are bound once per request, but the extra layer costs a call.

func OperationFromContext

func OperationFromContext(ctx context.Context) (*openapi.Operation, error)

OperationFromContext returns the OpenAPI operation of the route that is handling the request, or an error if none is found. ctx is the request context (c.Request.Context()) or a *gin.Context, which is read through its request even if gin's ContextWithFallback is off.

The operation is a deep copy of the one documented when the route was registered: each call returns a new one, and changing it affects neither the other callers nor the specification.

func Response

func Response(statusCode, desc string, model any, headers []*openapi.ResponseHeader, example any) func(*openapi.OperationInfo)

Response adds an additional response to the operation.

func ResponseWithExamples

func ResponseWithExamples(statusCode, desc string, model any, headers []*openapi.ResponseHeader, examples map[string]any) func(*openapi.OperationInfo)

ResponseWithExamples is a variant of Response that accept many examples.

func Security

func Security(security *openapi.SecurityRequirement) func(*openapi.OperationInfo)

Overrides top-level security requirement for this operation. Note that this function can be used more than once to add several requirements.

func StatusDescription

func StatusDescription(desc string) func(*openapi.OperationInfo)

StatusDescription sets the default status description of the operation.

func Summary

func Summary(summary string) func(*openapi.OperationInfo)

Summary adds a summary to an operation.

func Summaryf

func Summaryf(format string, a ...any) func(*openapi.OperationInfo)

Summaryf adds a summary to an operation according to a format specifier.

func WithOptionalSecurity

func WithOptionalSecurity() func(*openapi.OperationInfo)

Add an empty security requirement to this operation to make other security requirements optional.

func WithoutSecurity

func WithoutSecurity() func(*openapi.OperationInfo)

Remove any top-level security requirements for this operation.

func XCodeSample

func XCodeSample(cs *openapi.XCodeSample) func(*openapi.OperationInfo)

XCodeSample adds a code sample to the operation.

func XInternal

func XInternal() func(*openapi.OperationInfo)

XInternal marks the operation as internal.

Types

type ContentOption

type ContentOption func(*contentSpec)

ContentOption describes one media type of a request body: see Content.

func Content

func Content(mediaType string, model any, encs ...EncodingOption) ContentOption

Content describes the media type of a request body, whose schema is the one of model, as for any other type: a named struct is a component. A nil model gives a media type without a schema.

type DocsUI

type DocsUI struct {
	// contains filtered or unexported fields
}

DocsUI selects the renderer of Docs and its options. Build it with SwaggerUI or ScalarUI. The zero value is Swagger UI.

func EmbeddedScalarUI

func EmbeddedScalarUI(opts ...docsui.Option) DocsUI

EmbeddedScalarUI selects Scalar as the renderer of Docs, with its script served from the binary at <path>/assets/ instead of a CDN. The page makes no request to a third-party host. See EmbeddedSwaggerUI for the binary size.

func EmbeddedSwaggerUI

func EmbeddedSwaggerUI(opts ...docsui.Option) DocsUI

EmbeddedSwaggerUI selects Swagger UI as the renderer of Docs, with its assets served from the binary at <path>/assets/ instead of a CDN. The page makes no request to a third-party host.

Only a program that calls EmbeddedSwaggerUI or EmbeddedScalarUI carries the assets: the linker drops them otherwise. The Swagger UI 3.2 gaps listed at SwaggerUI apply.

func ScalarUI

func ScalarUI(opts ...docsui.Option) DocsUI

ScalarUI selects Scalar as the renderer of Docs.

func SwaggerUI

func SwaggerUI(opts ...docsui.Option) DocsUI

SwaggerUI selects Swagger UI as the renderer of Docs.

Swagger UI renders OpenAPI 3.2 only partly. Known gaps: itemSchema is not rendered (swagger-ui#11065) and the tag summary is not shown; tag kind and parent are unverified (see docs/compat.md). Use ScalarUI for fuller 3.2 rendering. The choice is always honored: fizz never falls back to another renderer.

type EncodingOption

type EncodingOption func(*encodingSpec)

EncodingOption sets the encoding of a property of a Content.

func Encoding

func Encoding(property, contentType string) EncodingOption

Encoding sets the content type of a property of the schema of a Content (the "encoding" of a media type). A property that the schema does not have is reported as a warning.

type Fizz

type Fizz struct {
	*RouterGroup
	// contains filtered or unexported fields
}

Fizz is an abstraction of a Gin engine that wraps the routes handlers with Tonic and generates an OpenAPI 3.2.1 specification from it.

func New

func New(opts ...Option) *Fizz

New creates a new Fizz wrapper for a default Gin engine.

Unless WithoutBindHook is passed, New calls InstallBindHook, which wraps the process-global tonic bind hook so that deepObject query parameters bind. This mutates global tonic state: every call re-wraps the current hook if it is not already fizz's, so a hook set before New is kept and composed. A hook set after New replaces fizz's; compose it with fizz.BindHook(next).

Example (Options)

This example reads the description from a "doc" tag and documents pointers as plain (non-null) types.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
	"github.com/KeisukeFD/fizz/openapi"
)

type optionsIn struct {
	Name *string `query:"name" doc:"Name filter"`
}

func main() {
	f := fizz.New(
		fizz.WithTagNames(openapi.TagNames{Description: "doc"}),
		fizz.WithPointersAreNullable(false),
	)
	f.GET("/pets", []fizz.OperationOption{fizz.ID("listPets")},
		tonic.Handler(func(*gin.Context, *optionsIn) error { return nil }, 200))

	op := f.Generator().API().Paths["/pets"].GET
	b, err := json.Marshal(op.Parameters[0])
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))
}
Output:
{"name":"name","in":"query","description":"Name filter","schema":{"type":"string"}}

func NewFromEngine

func NewFromEngine(e *gin.Engine, opts ...Option) *Fizz

NewFromEngine creates a new Fizz wrapper from an existing Gin engine.

func (*Fizz) Docs

func (f *Fizz) Docs(path, specURL string, ui ...DocsUI)

Docs registers a GET route at path that serves an interactive UI for the OpenAPI document served at specURL. The route is not part of the specification.

Without ui the renderer is Swagger UI, the default. Pass SwaggerUI or ScalarUI to choose one and set its options; the choice is always honored. More than one ui is a mistake: it is recorded in Errors and the first one is used.

Example

This example mounts a docs page for the specification: Swagger UI by default, Scalar or an embedded copy of either on request.

package main

import (
	"fmt"
	"net/http/httptest"
	"strings"

	"github.com/KeisukeFD/fizz"
	"github.com/KeisukeFD/fizz/openapi"
)

func main() {
	f := fizz.New()
	f.GET("/openapi.json", nil, f.OpenAPI(&openapi.Info{Title: "Pets", Version: "1.0.0"}, "json"))
	f.Docs("/docs", "/openapi.json")                              // Swagger UI, the default
	f.Docs("/scalar", "/openapi.json", fizz.ScalarUI())           // Scalar, from a CDN
	f.Docs("/offline", "/openapi.json", fizz.EmbeddedSwaggerUI()) // Swagger UI, from the binary

	for _, path := range []string{"/docs", "/scalar", "/offline"} {
		w := httptest.NewRecorder()
		f.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
		body := w.Body.String()
		fmt.Println(path, w.Code, strings.Contains(body, "swagger-ui"), strings.Contains(body, "scalar"))
	}
}
Output:
/docs 200 true false
/scalar 200 false true
/offline 200 true false

func (*Fizz) Document

func (f *Fizz) Document() (*openapi.OpenAPI, error)

Document returns the document as served by SpecHandler: a deep copy with the DocumentHook applied, which the caller may change. It is built once per generation, like the served encodings. An error of the hook or of the copy is returned, and recorded in Errors once per generation.

func (*Fizz) Engine

func (f *Fizz) Engine() *gin.Engine

Engine returns the underlying Gin engine.

func (*Fizz) Err

func (f *Fizz) Err() error

Err returns the errors that Errors reports, other than warnings, joined with errors.Join, or nil if there are none.

Example

This example reports a generation error. Registration never panics: the failing operation is left out of the document, the route is still served, and Err joins the errors that are not warnings.

package main

import (
	"errors"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
	"github.com/KeisukeFD/fizz/openapi"
)

func main() {
	f := fizz.New()
	h := tonic.Handler(func(*gin.Context) error { return nil }, 200)
	f.GET("/a", []fizz.OperationOption{fizz.ID("same")}, h)
	f.GET("/b", []fizz.OperationOption{fizz.ID("same")}, h)

	err := f.Err()
	fmt.Println(err)
	var opErr *openapi.OperationError
	if errors.As(err, &opErr) {
		fmt.Println(opErr.Method, opErr.Path)
	}
}
Output:
GET /b (same): ID same is already used by another operation
GET /b

func (*Fizz) Errors

func (f *Fizz) Errors() []error

Errors returns the errors that may have occurred during the spec generation.

func (*Fizz) Generator

func (f *Fizz) Generator() *openapi.Generator

Generator returns the underlying OpenAPI generator.

func (*Fizz) GinRouterGroup

func (f *Fizz) GinRouterGroup() *gin.RouterGroup

GinRouterGroup returns the underlying Gin router group.

func (*Fizz) OpenAPI

func (f *Fizz) OpenAPI(info *openapi.Info, ct string) gin.HandlerFunc

OpenAPI returns a Gin HandlerFunc that serves the marshalled OpenAPI specification of the API: it sets info as the Info of the document and wraps SpecHandler(ct), where ct is "json" (the default when empty) or "yaml". An invalid content type is recorded in Errors and the handler answers 500.

func (*Fizz) ServeHTTP

func (f *Fizz) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.HandlerFunc for Fizz.

func (*Fizz) SpecHandler

func (f *Fizz) SpecHandler(format string) http.Handler

SpecHandler returns an http.Handler that serves the OpenAPI specification of the API, as "json" or "yaml" (the case is ignored). It serves the document as of the time of each request, with the Info of the generator (see Generator().SetInfo), encoded once per change to the generator and shared by concurrent requests.

Any other format is recorded in Errors, once, and the handler answers 500 Internal Server Error.

type OperationOption

type OperationOption func(*openapi.OperationInfo)

OperationOption represents an option-pattern function used to add informations to an operation.

func CustomizeOperation

func CustomizeOperation(fn func(*openapi.Operation) error) OperationOption

CustomizeOperation adjusts the operation through fn, which runs on a copy of it once every other option has been applied (whatever the order of the options), and before the OperationHook. Several functions run in the order they are given. If fn returns an error its changes are discarded and the error is recorded with the operation ID; the next function still runs. The operation ID cannot be changed: a new one is reverted and a warning is recorded. A nil fn is ignored.

Example

This example edits the operation after every other option has been applied: CustomizeOperation runs last, whatever its position.

package main

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
	"github.com/KeisukeFD/fizz/openapi"
)

type optionsIn struct {
	Name *string `query:"name" doc:"Name filter"`
}

func main() {
	f := fizz.New()
	f.GET("/pets", []fizz.OperationOption{
		fizz.CustomizeOperation(func(op *openapi.Operation) error {
			op.Summary += " (beta)"
			return nil
		}),
		fizz.ID("listPets"),
		fizz.Summary("List pets"),
	}, tonic.Handler(func(*gin.Context, *optionsIn) error { return nil }, 200))

	doc, err := f.Document()
	if err != nil {
		panic(err)
	}
	fmt.Println(doc.Paths["/pets"].GET.Summary)
}
Output:
List pets (beta)

func Extension

func Extension(key string, value any) OperationOption

Extension sets the "x-" specification extension key of the operation to value, the last option of a key winning. An invalid key (openapi.ErrInvalidExtensionKey, openapi.ErrReservedExtension), a value that is not JSON-encodable, and a key that a typed option owns ("x-codeSamples" is XCodeSample's, "x-internal" is XInternal's) are recorded errors, and the extension is not emitted.

func ExternalDocs

func ExternalDocs(url, desc string) OperationOption

ExternalDocs sets the external documentation of the operation. An empty url is a recorded error and nothing is emitted.

func Parameter

func Parameter(p *openapi.Parameter) OperationOption

Parameter adds p to the parameters of the operation, or merges it into the inferred one that has the same name and location ("in"). It acts over what the input type, the tags and the ParameterHook give, and under the OperationHook.

The merge is field by field: each non-zero field of p replaces the inferred one (a non-nil pointer, slice or map is non-zero), so that a field p leaves out keeps its inferred value, the schema included. Schema and Content are replaced whole, not merged; Extensions are merged key by key. A bool that is false cannot unset a true one. Options on the same parameter apply in order, the last one winning. A parameter with no inferred match is appended.

A nil p is ignored, and p is copied: it may be reused. A parameter without a name or a location, a path parameter that is not in the path, and a merge into a $ref parameter are recorded errors; the operation is still added, without that parameter.

func RequestBody

func RequestBody(desc string, required bool, contents ...ContentOption) OperationOption

RequestBody adjusts the request body of the operation, over what the input type and the tags give (and under the OperationHook). desc is its description; required overrides the inferred required flag, in both directions. If contents are given they replace the inferred content entirely; a media type given twice is an error and the first is kept. Without contents the inferred content is kept, and it is an error if there is none. A request body is an error on GET and HEAD operations; DELETE may have one.

Example

This example documents a request body in XML instead of the JSON body inferred from the input, and marks it required.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
)

type exPet struct {
	Name string `json:"name"`
}

func main() {
	f := fizz.New()
	f.POST("/pets", []fizz.OperationOption{
		fizz.ID("createPet"),
		fizz.RequestBody("The pet to create", true,
			fizz.Content("application/xml", exPet{})),
	}, tonic.Handler(func(*gin.Context, *exPet) error { return nil }, 201))

	doc, err := f.Document()
	if err != nil {
		panic(err)
	}
	b, err := json.Marshal(doc.Paths["/pets"].POST.RequestBody)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))
}
Output:
{"description":"The pet to create","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Fizz_testExPet"}}},"required":true}

func ResponseWith

func ResponseWith(code, desc string, opts ...ResponseOption) OperationOption

ResponseWith adds a response to the operation, built the same way as the one of Response: same naming of the schemas, default media type and nullability. A code already used by the operation is an error.

The model, the example and the examples go under the default media type; WithContent adds other media types. WithExample together with WithExamples, and a media type given twice, are recorded errors (the examples, and the first media type, are kept).

func Tags

func Tags(tags ...string) OperationOption

Tags adds tags to the operation, after the tag of its group and without duplicates: a tag that is already there, and an empty one, are ignored. The tags of an operation are not declared at the root of the document; use Generator.SetTag for that.

type Option

type Option func(*config)

Option configures a Fizz instance. Options are passed to New and NewFromEngine and applied in order; nil options are ignored.

func WithAnnotationStyle

func WithAnnotationStyle(s openapi.AnnotationStyle) Option

WithAnnotationStyle selects how use-site annotations are attached to a schema that is a $ref. It defaults to openapi.SiblingAnnotations.

func WithDefaultMediaType

func WithDefaultMediaType(mediaType string) Option

WithDefaultMediaType sets the media type used for request bodies and responses. An empty string selects tonic.MediaType().

func WithHooks

func WithHooks(h openapi.Hooks) Option

WithHooks sets the generator hooks. The hooks of several calls compose in order: the Schema hooks all run; the Field and Parameter hooks run until one skips; the Operation and Document hooks run until one fails. A nil member is ignored. See openapi.Hooks for what each hook receives and openapi.Generator.SetHooks for the restrictions.

Example

This example adds an x-tagGroups extension to the served document with a DocumentHook. The hook edits a copy: Generator().API() is unchanged.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
	"github.com/KeisukeFD/fizz/openapi"
)

type optionsIn struct {
	Name *string `query:"name" doc:"Name filter"`
}

func main() {
	f := fizz.New(fizz.WithHooks(openapi.Hooks{
		Document: func(doc *openapi.OpenAPI) error {
			doc.XTagGroups = append(doc.XTagGroups, &openapi.XTagGroup{
				Name: "Pets",
				Tags: []string{"pets"},
			})
			return nil
		},
	}))
	f.GET("/pets", []fizz.OperationOption{fizz.ID("listPets")},
		tonic.Handler(func(*gin.Context, *optionsIn) error { return nil }, 200))

	doc, err := f.Document()
	if err != nil {
		panic(err)
	}
	b, err := json.Marshal(doc.XTagGroups)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))
}
Output:
[{"name":"Pets","tags":["pets"]}]
Example (Downgrade)

This example is a DocumentHook for a tool that cannot read OpenAPI 3.1 and later: it declares 3.0.3 and rewrites the one construct that this hook knows, the nullable type union. It is a starting point, not a converter: see MIGRATION.md for what it leaves out.

package main

import (
	"encoding/json"
	"fmt"
	"net/url"
	"reflect"
	"slices"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/loopfz/gadgeto/tonic"

	"github.com/KeisukeFD/fizz"
	"github.com/KeisukeFD/fizz/openapi"
)

type migrateModel struct {
	Wait time.Duration `json:"wait"`
	Home url.URL       `json:"home"`
	Nick *string       `json:"nick"`
	Data []byte        `json:"data"`
}

func main() {
	f := fizz.New(fizz.WithHooks(openapi.Hooks{
		Document: func(doc *openapi.OpenAPI) error {
			doc.OpenAPI = "3.0.3"
			var visit func(*openapi.Schema)
			visit = func(s *openapi.Schema) {
				if s == nil {
					return
				}
				if i := slices.Index(s.Type, "null"); i >= 0 {
					s.Type = slices.Delete(slices.Clone(s.Type), i, i+1)
					s.Extensions = map[string]any{"nullable": true}
				}
				for _, p := range s.Properties {
					visit(p)
				}
				visit(s.Items)
			}
			for _, s := range doc.Components.Schemas {
				visit(s)
			}
			return nil
		},
	}), fizz.WithSchemaNamer(func(t reflect.Type) string { return t.Name() }))
	f.GET("/model", []fizz.OperationOption{fizz.ID("getModel")},
		tonic.Handler(func(*gin.Context) (*migrateModel, error) { return nil, nil }, 200))

	doc, err := f.Document()
	if err != nil {
		panic(err)
	}
	b, err := json.Marshal(doc.Components.Schemas["migrateModel"].Properties["nick"])
	if err != nil {
		panic(err)
	}
	fmt.Println(doc.OpenAPI, string(b))
}
Output:
3.0.3 {"type":"string","nullable":true}

func WithOperationIDNamer

func WithOperationIDNamer(fn func(method, path, handlerName string) string) Option

WithOperationIDNamer sets the function that derives the ID of an operation registered without fizz.ID. It receives the HTTP method, the OpenAPI path (for example "/users/{id}") and the full runtime name of the handler (for example "github.com/x/pkg.(*T).Method-fm"). It is not called when fizz.ID is set. An empty result selects the default naming. If the ID it returns is already used, the ID falls back to the method and path ("get_users_id"). A nil function selects the default naming.

func WithPointersAreNullable

func WithPointersAreNullable(b bool) Option

WithPointersAreNullable controls whether a pointer type also accepts null in the generated schema. It defaults to true.

func WithRequestBodyNamer

func WithRequestBodyNamer(fn func(opID string, t reflect.Type) string) Option

WithRequestBodyNamer sets the function that names the component schema of a request body from the operation ID and the input type. A nil function, or an empty name, selects the default: the operation ID with its first letter upper-cased, followed by "Input".

func WithSchemaNamer

func WithSchemaNamer(fn func(reflect.Type) string) Option

WithSchemaNamer sets the function that names the component schema of a type. A nil function selects the default naming.

func WithTagNames

func WithTagNames(n openapi.TagNames) Option

WithTagNames sets the names of the fizz-owned struct tags. A zero field keeps the default name and "-" disables that tag. The binder tags (path, query, header, enum, default, validate, explode) are fixed to tonic's and cannot be renamed.

func WithoutBindHook

func WithoutBindHook() Option

WithoutBindHook stops New and NewFromEngine from calling InstallBindHook, which wraps the process-global tonic bind hook to bind deepObject query parameters and cookie parameters. Without the hook those parameters are documented but not bound, unless you install it yourself with InstallBindHook or tonic.SetBindHook(fizz.BindHook(next)). It does not remove a hook that an earlier New already installed.

type ResponseOption

type ResponseOption func(*responseSpec)

ResponseOption sets a part of a response added by ResponseWith.

func WithContent

func WithContent(mediaType string, model any) ResponseOption

WithContent adds a media type to the response, whose schema is the one of model. A nil model gives a media type without a schema.

func WithExample

func WithExample(example any) ResponseOption

WithExample sets the example of the response, under the default media type. It excludes WithExamples.

func WithExamples

func WithExamples(examples map[string]any) ResponseOption

WithExamples sets the named examples of the response, under the default media type. It excludes WithExample.

func WithHeaders

func WithHeaders(headers ...*openapi.ResponseHeader) ResponseOption

WithHeaders adds headers to the response.

func WithModel

func WithModel(model any) ResponseOption

WithModel sets the type of the body of the response, under the default media type.

func WithResponseExtension

func WithResponseExtension(key string, value any) ResponseOption

WithResponseExtension sets the "x-" extension key of the response, with the rules of Extension.

type RouterGroup

type RouterGroup struct {
	Name        string
	Description string
	// contains filtered or unexported fields
}

RouterGroup is an abstraction of a Gin router group.

func (*RouterGroup) DELETE

func (g *RouterGroup) DELETE(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup

DELETE is a shortcut to register a new handler with the DELETE method.

func (*RouterGroup) GET

func (g *RouterGroup) GET(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup

GET is a shortcut to register a new handler with the GET method.

func (*RouterGroup) GinRouterGroup

func (g *RouterGroup) GinRouterGroup() *gin.RouterGroup

GinRouterGroup returns the underlying Gin router group.

func (*RouterGroup) Group

func (g *RouterGroup) Group(path, name, description string, handlers ...gin.HandlerFunc) *RouterGroup

Group creates a new group of routes.

func (*RouterGroup) HEAD

func (g *RouterGroup) HEAD(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup

HEAD is a shortcut to register a new handler with the HEAD method.

func (*RouterGroup) Handle

func (g *RouterGroup) Handle(path, method string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup

Handle registers a new request handler that is wrapped with Tonic and documented in the OpenAPI specification.

func (*RouterGroup) OPTIONS

func (g *RouterGroup) OPTIONS(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup

OPTIONS is a shortcut to register a new handler with the OPTIONS method.

func (*RouterGroup) PATCH

func (g *RouterGroup) PATCH(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup

PATCH is a shortcut to register a new handler with the PATCH method.

func (*RouterGroup) POST

func (g *RouterGroup) POST(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup

POST is a shortcut to register a new handler with the POST method.

func (*RouterGroup) PUT

func (g *RouterGroup) PUT(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup

PUT is a shortcut to register a new handler with the PUT method.

func (*RouterGroup) TRACE

func (g *RouterGroup) TRACE(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup

TRACE is a shortcut to register a new handler with the TRACE method.

func (*RouterGroup) Use

func (g *RouterGroup) Use(handlers ...gin.HandlerFunc)

Use adds middleware to the group.

Directories

Path Synopsis
Package bind binds HTTP request parameters (query, cookies, headers and path parameters) to Go values without depending on any router.
Package bind binds HTTP request parameters (query, cookies, headers and path parameters) to Go values without depending on any router.
Package docsui serves interactive API documentation UIs (Swagger UI, Scalar) as plain http.Handler values, without depending on any router.
Package docsui serves interactive API documentation UIs (Swagger UI, Scalar) as plain http.Handler values, without depending on any router.
embedded
Package embedded serves the docs UIs from assets embedded in the binary.
Package embedded serves the docs UIs from assets embedded in the binary.
internal/pinassets command
Command pinassets downloads the pinned docs UI assets into docsui/embedded/assets and checks (or rewrites) the SRI constants in package docsui.
Command pinassets downloads the pinned docs UI assets into docsui/embedded/assets and checks (or rewrites) the SRI constants in package docsui.
examples
market command
internal
acceptance/at
Package at is the acceptance-test harness: small helpers to drive a fizz under test and assert on what it serves.
Package at is the acceptance-test harness: small helpers to drive a fizz under test and assert on what it serves.
acceptance/fixtures/naming/fixtures
Package fixtures holds a generic type, to check the component names of its instantiations.
Package fixtures holds a generic type, to check the component names of its instantiations.
acceptance/fixtures/naming/x
Package models is the first of two same-named fixture packages.
Package models is the first of two same-named fixture packages.
acceptance/fixtures/naming/y
Package models is the second of two same-named fixture packages.
Package models is the second of two same-named fixture packages.
conformance
Package conformance holds the official-spec conformance suite (see docs/plan/PLAN-v2.md, Phase 10).
Package conformance holds the official-spec conformance suite (see docs/plan/PLAN-v2.md, Phase 10).
conformance/contract
Package contract holds the spec-driven contract tests (docs/plan/PLAN-v2.md, P10.6).
Package contract holds the spec-driven contract tests (docs/plan/PLAN-v2.md, P10.6).
conformance/internal/fetchoai command
Command fetchoai downloads the pinned official OpenAPI Initiative material into internal/conformance/oai and checks (or rewrites) MANIFEST.json.
Command fetchoai downloads the pinned official OpenAPI Initiative material into internal/conformance/oai and checks (or rewrites) MANIFEST.json.
conformance/internal/upgradeoai command
Command upgradeoai regenerates internal/conformance/oai/upgraded and the generated section of oai/NOTICE from the pristine files under oai/orig.
Command upgradeoai regenerates internal/conformance/oai/upgraded and the generated section of oai/NOTICE from the pristine files under oai/orig.
conformance/oai
Package oai holds the vendored official OpenAPI Initiative material used by the conformance suite (see docs/plan/PLAN-v2.md, Phase 10).
Package oai holds the vendored official OpenAPI Initiative material used by the conformance suite (see docs/plan/PLAN-v2.md, Phase 10).
conformance/repro
Package repro is the harness of the reproduction apps (docs/plan/PLAN-v2.md, P10.5, decision D23).
Package repro is the harness of the reproduction apps (docs/plan/PLAN-v2.md, P10.5, decision D23).
conformance/repro/apiwithexamples
Package apiwithexamples rebuilds learn.openapis.org examples/v3.0/api-with-examples.json with the public fizz API.
Package apiwithexamples rebuilds learn.openapis.org examples/v3.0/api-with-examples.json with the public fizz API.
conformance/repro/baseuriretrieval
Package baseuriretrieval rebuilds the spec-text document base-uri-from-the-retrieval-uri-1 (a request body component whose schema is a relative $ref) with the public fizz API.
Package baseuriretrieval rebuilds the spec-text document base-uri-from-the-retrieval-uri-1 (a request body component whose schema is a relative $ref) with the public fizz API.
conformance/repro/callback
Package callback rebuilds learn.openapis.org examples/v3.0/callback-example.json with the public fizz API.
Package callback rebuilds learn.openapis.org examples/v3.0/callback-example.json with the public fizz API.
conformance/repro/link
Package link rebuilds learn.openapis.org examples/v3.0/link-example.json with the public fizz API.
Package link rebuilds learn.openapis.org examples/v3.0/link-example.json with the public fizz API.
conformance/repro/nonoauthscopes
Package nonoauthscopes rebuilds learn.openapis.org examples/v3.1/non-oauth-scopes.json with the public fizz API.
Package nonoauthscopes rebuilds learn.openapis.org examples/v3.1/non-oauth-scopes.json with the public fizz API.
conformance/repro/petstore
Package petstore rebuilds learn.openapis.org examples/v3.0/petstore.json with the public fizz API.
Package petstore rebuilds learn.openapis.org examples/v3.0/petstore.json with the public fizz API.
conformance/repro/petstoreexpanded
Package petstoreexpanded rebuilds learn.openapis.org examples/v3.0/petstore-expanded.json with the public fizz API.
Package petstoreexpanded rebuilds learn.openapis.org examples/v3.0/petstore-expanded.json with the public fizz API.
conformance/repro/query32
Package query32 rebuilds learn.openapis.org examples/v3.2/3.2-query-example.json with the public fizz API.
Package query32 rebuilds learn.openapis.org examples/v3.2/3.2-query-example.json with the public fizz API.
conformance/repro/tags32
Package tags32 rebuilds learn.openapis.org examples/v3.2/3.2-tags-example.json with the public fizz API.
Package tags32 rebuilds learn.openapis.org examples/v3.2/3.2-tags-example.json with the public fizz API.
conformance/repro/tictactoe
Package tictactoe rebuilds learn.openapis.org examples/v3.1/tictactoe.json with the public fizz API.
Package tictactoe rebuilds learn.openapis.org examples/v3.1/tictactoe.json with the public fizz API.
conformance/repro/uspto
Package uspto rebuilds learn.openapis.org examples/v3.0/uspto.json with the public fizz API.
Package uspto rebuilds learn.openapis.org examples/v3.0/uspto.json with the public fizz API.
conformance/repro/webhook
Package webhook rebuilds learn.openapis.org examples/v3.1/webhook-example.json with the public fizz API.
Package webhook rebuilds learn.openapis.org examples/v3.1/webhook-example.json with the public fizz API.
conformance/upgrade
Package upgrade converts official OpenAPI example documents to OAS 3.2.1 and extracts the YAML examples of the specification text.
Package upgrade converts official OpenAPI example documents to OAS 3.2.1 and extracts the YAML examples of the specification text.
golden
Package golden compares generated output against golden files.
Package golden compares generated output against golden files.
kitchensink
Package kitchensink is a catalogue of small registration cases, each carrying hand-written expectations of the OAS 3.2 target output.
Package kitchensink is a catalogue of small registration cases, each carrying hand-written expectations of the OAS 3.2 target output.
kitchensink/a/models
Package models is a seed model package.
Package models is a seed model package.
kitchensink/b/models
Package models is a seed model package that deliberately shares its package name with ../../a/models, to test name collisions.
Package models is a seed model package that deliberately shares its package name with ../../a/models, to test name collisions.
kitchensink/generic
Package generic holds seed generic types for kitchen-sink cases.
Package generic holds seed generic types for kitchen-sink cases.
scalar
Package scalar holds the one notion of a scalar shared by bind, which decodes parameters, and openapi, which describes them: the two must agree on which types decode from one string.
Package scalar holds the one notion of a scalar shared by bind, which decodes parameters, and openapi, which describes them: the two must agree on which types decode from one string.
specvalidate
Package specvalidate validates generated OpenAPI documents against the official OAS 3.2 JSON Schemas (targeting 3.2.1), vendored under schemas/3.2 and loaded offline.
Package specvalidate validates generated OpenAPI documents against the official OAS 3.2 JSON Schemas (targeting 3.2.1), vendored under schemas/3.2 and loaded offline.
internal/vtag
Package vtag parses go-playground/validator v9 `validate` struct tags.
Package vtag parses go-playground/validator v9 `validate` struct tags.

Jump to

Keyboard shortcuts

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