Documentation
¶
Overview ¶
Example (Cookie) ¶
This example binds cookie parameters. A cookie that is absent takes the default tag value; New installs the tonic bind hook that does it.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/gin-gonic/gin"
"github.com/loopfz/gadgeto/tonic"
"github.com/KeisukeFD/fizz"
)
type cookieIn struct {
Session string `cookie:"session"`
Lang string `cookie:"lang" default:"en"`
}
func main() {
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)
}
Output: session=abc lang=en
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 ¶
- Variables
- func BindHook(next tonic.BindHook) tonic.BindHook
- func DefaultResponseExamples(examples map[string]any) func(*openapi.OperationInfo)
- func Deprecated(deprecated bool) func(*openapi.OperationInfo)
- func Description(desc string) func(*openapi.OperationInfo)
- func Descriptionf(format string, a ...any) func(*openapi.OperationInfo)
- func Header(name, desc string, model any) func(*openapi.OperationInfo)
- func ID(id string) func(*openapi.OperationInfo)
- func InputModel(model any) func(*openapi.OperationInfo)
- func InstallBindHook()
- func OperationFromContext(ctx context.Context) (*openapi.Operation, error)
- func Response(statusCode, desc string, model any, headers []*openapi.ResponseHeader, ...) func(*openapi.OperationInfo)
- func ResponseWithExamples(statusCode, desc string, model any, headers []*openapi.ResponseHeader, ...) func(*openapi.OperationInfo)
- func Security(security *openapi.SecurityRequirement) func(*openapi.OperationInfo)
- func StatusDescription(desc string) func(*openapi.OperationInfo)
- func Summary(summary string) func(*openapi.OperationInfo)
- func Summaryf(format string, a ...any) func(*openapi.OperationInfo)
- func WithOptionalSecurity() func(*openapi.OperationInfo)
- func WithoutSecurity() func(*openapi.OperationInfo)
- func XCodeSample(cs *openapi.XCodeSample) func(*openapi.OperationInfo)
- func XInternal() func(*openapi.OperationInfo)
- type ContentOption
- type DocsUI
- type EncodingOption
- type Fizz
- func (f *Fizz) Docs(path, specURL string, ui ...DocsUI)
- func (f *Fizz) Document() (*openapi.OpenAPI, error)
- func (f *Fizz) Engine() *gin.Engine
- func (f *Fizz) Err() error
- func (f *Fizz) Errors() []error
- func (f *Fizz) Generator() *openapi.Generator
- func (f *Fizz) GinRouterGroup() *gin.RouterGroup
- func (f *Fizz) OpenAPI(info *openapi.Info, ct string) gin.HandlerFunc
- func (f *Fizz) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (f *Fizz) SpecHandler(format string) http.Handler
- type OperationOption
- func CustomizeOperation(fn func(*openapi.Operation) error) OperationOption
- func Extension(key string, value any) OperationOption
- func ExternalDocs(url, desc string) OperationOption
- func Parameter(p *openapi.Parameter) OperationOption
- func RequestBody(desc string, required bool, contents ...ContentOption) OperationOption
- func ResponseWith(code, desc string, opts ...ResponseOption) OperationOption
- func Tags(tags ...string) OperationOption
- type Option
- func WithAnnotationStyle(s openapi.AnnotationStyle) Option
- func WithDefaultMediaType(mediaType string) Option
- func WithHooks(h openapi.Hooks) Option
- func WithOperationIDNamer(fn func(method, path, handlerName string) string) Option
- func WithPointersAreNullable(b bool) Option
- func WithRequestBodyNamer(fn func(opID string, t reflect.Type) string) Option
- func WithSchemaNamer(fn func(reflect.Type) string) Option
- func WithTagNames(n openapi.TagNames) Option
- func WithoutBindHook() Option
- type ResponseOption
- func WithContent(mediaType string, model any) ResponseOption
- func WithExample(example any) ResponseOption
- func WithExamples(examples map[string]any) ResponseOption
- func WithHeaders(headers ...*openapi.ResponseHeader) ResponseOption
- func WithModel(model any) ResponseOption
- func WithResponseExtension(key string, value any) ResponseOption
- type RouterGroup
- func (g *RouterGroup) DELETE(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup
- func (g *RouterGroup) GET(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup
- func (g *RouterGroup) GinRouterGroup() *gin.RouterGroup
- func (g *RouterGroup) Group(path, name, description string, handlers ...gin.HandlerFunc) *RouterGroup
- func (g *RouterGroup) HEAD(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup
- func (g *RouterGroup) Handle(path, method string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup
- func (g *RouterGroup) OPTIONS(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup
- func (g *RouterGroup) PATCH(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup
- func (g *RouterGroup) POST(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup
- func (g *RouterGroup) PUT(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup
- func (g *RouterGroup) TRACE(path string, infos []OperationOption, handlers ...gin.HandlerFunc) *RouterGroup
- func (g *RouterGroup) Use(handlers ...gin.HandlerFunc)
Examples ¶
- Package (Cookie)
- Package (DeepObject)
- Package (Interfaces)
- Package (MigrateAPICopy)
- Package (MigrateBindHook)
- Package (MigrateDeleteBody)
- Package (MigrateEnumRef)
- Package (MigrateErrors)
- Package (MigrateModel)
- Package (MigrateOperationFromContext)
- Package (MigrateOperationIDs)
- Package (MigrateRecordedErrors)
- Package (MigrateTagNames)
- Package (MigrateTypes)
- Package (MigrateYAML)
- Package (Naming)
- Package (Tags)
- Package (Yaml)
- CustomizeOperation
- Fizz.Docs
- Fizz.Err
- New (Options)
- RequestBody
- WithHooks
- WithHooks (Downgrade)
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
func Header(name, desc string, model any) func(*openapi.OperationInfo)
Header adds a header to the operation.
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 ¶
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 ¶
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 ¶
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 SwaggerUI ¶
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 ¶
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 ¶
NewFromEngine creates a new Fizz wrapper from an existing Gin engine.
func (*Fizz) Docs ¶
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 ¶
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) Err ¶
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) GinRouterGroup ¶
func (f *Fizz) GinRouterGroup() *gin.RouterGroup
GinRouterGroup returns the underlying Gin router group.
func (*Fizz) OpenAPI ¶
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 ¶
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 ¶
WithDefaultMediaType sets the media type used for request bodies and responses. An empty string selects tonic.MediaType().
func WithHooks ¶
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 ¶
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 ¶
WithPointersAreNullable controls whether a pointer type also accepts null in the generated schema. It defaults to true.
func WithRequestBodyNamer ¶
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 ¶
WithSchemaNamer sets the function that names the component schema of a type. A nil function selects the default naming.
func WithTagNames ¶
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.
Source Files
¶
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. |
