### Initialize Fizz and Start HTTP Server Source: https://github.com/wi2l/fizz/blob/master/README.md Demonstrates initializing a Fizz instance from a Gin engine and using it as the handler for an HTTP server. It shows how to pass an existing Gin engine, register global middlewares, and then start the server with the Fizz instance. ```go engine := gin.Default() engine.Use(...) // register global middlewares f := fizz.NewFromEngine(engine) ``` ```go srv := &http.Server{ Addr: ":4242", Handler: f, } srv.ListenAndServe() ``` -------------------------------- ### Install Markdown Builder Source: https://github.com/wi2l/fizz/blob/master/markdown/README.md Shows the command to install the Markdown builder library using Go's package manager. ```bash go get -u github.com/wI2L/fizz ``` -------------------------------- ### Implement Exampler Interface for Custom Type Examples Source: https://github.com/wi2l/fizz/blob/master/README.md Implement the Exampler interface to provide custom example values for your types in OpenAPI specifications. The ParseExample method receives a string value from the 'example' tag and returns the parsed example. ```go type Exampler interface { ParseExample(v string) (interface{}, error) } ``` -------------------------------- ### Run Example API and Retrieve Specification Source: https://github.com/wi2l/fizz/blob/master/README.md Instructions on how to build and run a sample Fizz API, and then retrieve its generated OpenAPI specification in JSON format using curl. ```shell go build ./market # Retrieve the specification marshaled in JSON. curl -i http://localhost:4242/openapi.json ``` -------------------------------- ### OpenAPI Schema Example for Custom Type Source: https://github.com/wi2l/fizz/blob/master/README.md An example of an OpenAPI schema generated for a custom Go type that implements the DataType interface, showing how it appears as a string with a specific format. ```json { "type": "string", "format": "uuid" } ``` -------------------------------- ### OpenAPI/Tonic Tags for Parameter Specification Source: https://github.com/wi2l/fizz/blob/master/README.md Details common tags used to enrich OpenAPI specifications and control binding behavior in tonic. Includes 'default', 'description', 'deprecated', 'enum', 'example', 'format', 'validate', and 'explode' with their purposes and accepted values. ```APIDOC | name | description | | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `default` | *tonic* will bind this value if none was passed with the request. This should not be used if a field is also required. Read the [documentation](https://swagger.io/docs/specification/describing-parameters/) (section _Common Mistakes_) for more informations about this behaviour. | | `description` | Add a description of the field in the spec. | | `deprecated` | Indicates if the field is deprecated. Accepted values are `1`, `t`, `T`, `TRUE`, `true`, `True`, `0`, `f`, `F`, `FALSE`. Invalid value are considered to be false. | | `enum` | A coma separated list of acceptable values for the parameter. | | `example` | An example value to be used in OpenAPI specification. See [section below](#Providing-Examples-for-Custom-Types) for the demonstration on how to provide example for custom types. | | `format` | Override the format of the field in the specification. Read the [documentation](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#dataTypeFormat) for more informations. | | `validate` | Field validation rules. Read the [documentation](https://godoc.org/gopkg.in/go-playground/validator.v8) for more informations. | | `explode` | Specifies whether arrays should generate separate parameters for each array item or object property (limited to query parameters with *form* style). Accepted values are `1`, `t`, `T`, `TRUE`, `true`, `True`, `0`, `f`, `F`, `FALSE`. Invalid value are considered to be false. | ``` -------------------------------- ### Go Request Body Handling and OpenAPI Generation Source: https://github.com/wi2l/fizz/blob/master/README.md Explains how to use Go tags like `validate:"required"` and `binding:"-"` for request body validation and exclusion. Also covers OpenAPI generator behavior for request bodies with GET, DELETE, and HEAD methods, noting these methods are not allowed to have request bodies. ```APIDOC Request body handling: - Use `validate:"required"` to make a request body field mandatory. - Use a pointer type to differentiate between a missing value and a zero value. - Use `binding:"-"` to explicitly ignore a parameter from the request body. - OpenAPI generator ignores request body parameters for routes with methods GET, DELETE, or HEAD, as per RFC 7231. ``` -------------------------------- ### Fizz Operation Configuration Options Source: https://github.com/wi2l/fizz/blob/master/README.md Details various functions provided by the Fizz framework to configure and enrich API operations for OpenAPI specification generation. These include setting descriptions, summaries, IDs, deprecation status, defining responses with models and examples, managing headers, overriding input models, and controlling security requirements. ```APIDOC fizz.StatusDescription(desc string) - Sets the default response description. A default status text will be created from the code if it is omitted. fizz.Summary(summary string) fizz.Summaryf(format string, a ...interface{}) - Sets the summary of the operation. fizz.Description(desc string) fizz.Descriptionf(format string, a ...interface{}) - Sets the description of the operation. fizz.ID(id string) - Overrides the ID of the operation. Must be a unique string used to identify the operation among all operations described in the API. fizz.Deprecated(deprecated bool) - Marks the operation as deprecated. fizz.Response(statusCode, desc string, model interface{}, headers []*ResponseHeader, example interface{}) - Adds an additional response to the operation. The example argument populates a single example in the response schema. The statusCode can be a string like "default". fizz.ResponseWithExamples(statusCode, desc string, model interface{}, headers []*ResponseHeader, examples map[string]interface{}) - A variant of Response that supports providing multiple examples. The examples argument populates multiple examples in the response schema. fizz.Header(name, desc string, model interface{}) - Adds 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.InputModel(model interface{}) - Overrides the operation input model. The developer must ensure the binding matches the OpenAPI specification. fizz.Security(security *openapi.SecurityRequirement) - Overrides the top-level security requirement of an operation. Can be used multiple times to add several requirements. fizz.WithOptionalSecurity() - Adds an empty security requirement to this operation to make other security requirements optional. fizz.WithoutSecurity() - Removes any top-level security requirements for this operation. fizz.XCodeSample(codeSample *XCodeSample) - Adds a Code Sample to the operation. fizz.XInternal() - Marks the operation as internal. The x-internal flag impacts visual documentation rendering. ``` -------------------------------- ### Recursive Embedding Limitation Example Source: https://github.com/wi2l/fizz/blob/master/README.md Illustrates Go struct definitions that demonstrate limitations in recursive embedding for OpenAPI schema generation. Fields that directly or indirectly embed the same type are flagged as unsupported. ```go type A struct { Foo int *A // ko, embedded and same type as parent A *A // ok, not embedded *B // ok, different type } type B struct { Bar string *A // ko, type B is embedded in type A *C // ok, type C does not contains an embedded field of type A } type C struct { Baz bool } ``` -------------------------------- ### Serve OpenAPI Specification with Fizz Source: https://github.com/wi2l/fizz/blob/master/README.md Demonstrates how to use the `fizz.OpenAPI` method to serve the generated OpenAPI specification in JSON or YAML format. It requires an `openapi.Info` object containing metadata like title, description, and version. ```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")) ``` -------------------------------- ### Build Markdown Content with Go Builder Source: https://github.com/wi2l/fizz/blob/master/markdown/README.md Demonstrates the basic usage of the Markdown builder in Go, showing how to chain methods to create headers, paragraphs, and lists. ```go import "github.com/wI2L/fizz/markdown" builder := markdown.Builder{} builder. H1("Markdown Builder"). P("A simple builder to help your write Markdown in Go"). H2("Installation"). Code("go get -u github.com/wI2L/fizz", "bash"). H2("Todos"). BulletedList( "write tests", builder.Block().NumberedList("A", "B", "C"), "add more markdown features", ) md := builder.String() ``` -------------------------------- ### Create GitHub Flavored Markdown Table Source: https://github.com/wi2l/fizz/blob/master/markdown/README.md Illustrates how to generate a Markdown table with GitHub Flavored Markdown extensions, including alignment options. ```go builder.Table( [][]string{ []string{"Letter", "Title", "ID"}, []string{"A", "The Good", "500"}, []string{"B", "The Very very Bad Man", "2885645"}, []string{"C", "The Ugly"}, []string{"D", "The\nGopher", "800"}, },[]markdown.TableAlignment{ markdown.AlignCenter, markdown.AlignCenter, markdown.AlignRight, } ) ``` -------------------------------- ### Configure API Server Information in Fizz Source: https://github.com/wi2l/fizz/blob/master/README.md Shows how to declare server information for APIs not hosted on the same domain or using different path prefixes. This is achieved using the `f.Generator().SetServers` method with a slice of `openapi.Server` objects. ```go f := fizz.New() f.Generator().SetServers([]*openapi.Server{ { Description: "Fruits Market - production", URL: "https://example.org/api/1.0", }, }) ``` -------------------------------- ### Wrapping a Handler with Tonic Source: https://github.com/wi2l/fizz/blob/master/README.md Demonstrates how to wrap a handler function using `tonic.Handler`. This method takes the handler function and a default status code, returning a `gin.HandlerFunc` compatible with Gin/Fizz routing. ```go func MyHandler() gin.HandlerFunc { // The handler function takes a gin.Context and returns an error. // The second argument to tonic.Handler is the default HTTP status code. return tonic.Handler(func(c *gin.Context) error {}, 200) } ``` -------------------------------- ### Fizz Route Grouping Source: https://github.com/wi2l/fizz/blob/master/README.md Demonstrates how to create groups of routes in Fizz, similar to Gin. Fizz's Group method accepts optional 'name' and 'description' parameters, which are used to create tags in the OpenAPI specification applied to all routes within the group. Subgroups can be nested infinitely. ```go grp := f.Group("/subpath", "MyGroup", "Group description", middlewares...) // Example of nested groups: foo := f.Group("/foo", "Foo", "Foo group") bar := f.Group("/bar", "Bar", "Bar group") // All routes registered on group bar will have a relative path starting with /foo/bar // Example route within a group: bar.GET("/:barID", nil, tonic.Handler(MyBarHandler, 200)) // Registering middlewares on a group: grp.Use(middleware1, middleware2, ...) ``` -------------------------------- ### Tonic Parameter Binding Struct Tags Source: https://github.com/wi2l/fizz/blob/master/README.md Shows how to use struct tags (`path`, `query`, `header`) to define where Tonic should extract parameters from. Fields without these tags are assumed to be part of the request body. ```APIDOC type MyHandlerParams struct { ID int64 `path:"id"` Foo string `query:"foo"` Bar time.Time `header:"x-foo-bar"` } // Explanation of tags: // `path:"name"`: Binds from the request path parameter named 'name'. Path parameters are always required. // `query:"name"`: Binds from the request query string parameter named 'name'. // `header:"name"`: Binds from the request header named 'name'. // Fields without tags are bound from the request body. ``` -------------------------------- ### Configure API Security Schemes and Requirements Source: https://github.com/wi2l/fizz/blob/master/README.md Details how to declare security schemes for API authentication using `f.Generator().SetSecuritySchemes`. It also shows how to apply these schemes to operations using `fizz.Security` with `openapi.SecurityRequirement`. ```go f := fizz.New() f.Generator().SetSecuritySchemes(map[string]*openapi.SecuritySchemeOrRef{ "apiToken": { SecurityScheme: &openapi.SecurityScheme{ Type: "apiKey", In: "header", Name: "x-api-token", }, }, }) // Applying security to an operation: fizz.Security(&openapi.SecurityRequirement{ "apiToken": []string{}, }) ``` -------------------------------- ### Go Struct Tags for JSON/XML and OpenAPI Generation Source: https://github.com/wi2l/fizz/blob/master/README.md Demonstrates Go struct tags like `json:"-"` and `binding:"-"` to control field inclusion in JSON/XML encoding and OpenAPI specifications. Fields tagged with `"-"` are omitted from encoding or parameter binding. ```Go type Model struct { Input string `json:"-"` Output string `json:"output" binding:"-"` } ``` -------------------------------- ### Go Primitive Types for Headers Source: https://github.com/wi2l/fizz/blob/master/README.md Predefined variables for Go primitive types that can be used as the third argument (model) of the `fizz.Header` method to declare additional headers. ```go var ( Integer int32 Long int64 Float float32 Double float64 String string Byte []byte Binary []byte Boolean bool DateTime time.Time ) ``` -------------------------------- ### Tonic Handler Function Signature Source: https://github.com/wi2l/fizz/blob/master/README.md Defines the expected signature for handlers wrapped by the Tonic package. It accepts a gin.Context and an optional input object pointer, returning an output object and an error. The minimal signature omits input/output objects. ```go func(*gin.Context, [input object ptr]) ([output object], error) // Minimal accepted signature: func(*gin.Context) error ``` -------------------------------- ### Register Gin Handlers with Tonic for OpenAPI Spec Source: https://github.com/wi2l/fizz/blob/master/README.md Illustrates registering Gin handlers with Fizz, emphasizing the use of `tonic.Handler` for a specific handler. The input and output types of the `tonic.Handler`-wrapped function are used by Fizz to generate the OpenAPI specification for the operation. Standard `gin.HandlerFunc` signatures are also supported but ignored by the OpenAPI generator. ```go func BarHandler(c *gin.Context) { ... } func FooHandler(*gin.Context, *Foo) (*Bar, error) { ... } fizz := fizz.New() fizz.GET("/foo/bar", nil, BarHandler, tonic.Handler(FooHandler, 200)) ``` -------------------------------- ### Implement DataType Interface for Custom Schema Source: https://github.com/wi2l/fizz/blob/master/README.md Implement the DataType interface for custom Go types to manually control their OpenAPI schema output. This allows specifying the schema type and format, overriding default reflection-based generation. ```go type UUIDv4 struct { ... } func (*UUIDv4) Format() string { return "uuid" } func (*UUIDv4) Type() string { return "string" } ``` -------------------------------- ### Customize OpenAPI Component Type Names Source: https://github.com/wi2l/fizz/blob/master/README.md Explains how to customize the names of output types registered as components in the OpenAPI specification. This can be done globally via `f.Generator().OverrideTypeName` or by implementing the `openapi.Typer` interface on custom types. ```go import "reflect" // Global override f := fizz.New() f.Generator().OverrideTypeName(reflect.TypeOf(T{}), "OverridedName") // Interface implementation // func (*T) TypeName() string { return "OverridedName" } ``` -------------------------------- ### Implement Nullable Interface for Nullable Properties Source: https://github.com/wi2l/fizz/blob/master/README.md Implement the Nullable interface to explicitly mark Go types as nullable in OpenAPI schemas. This is useful for types like sql.NullString when they are not referenced by a pointer but should still be considered nullable. ```go type NullString sql.NullString func (NullString) Nullable() bool { return true } ``` -------------------------------- ### Setting Operation ID for Handlers Source: https://github.com/wi2l/fizz/blob/master/README.md Illustrates how to explicitly set an operation ID for a handler when using closures or when multiple handlers might otherwise have the same name, preventing generator errors. ```go fizz.GET("/foo", []fizz.OperationOption{ fizz.ID("MyOperationID") }, MyHandler()) ``` -------------------------------- ### Override Schema Type and Format Manually Source: https://github.com/wi2l/fizz/blob/master/README.md Use the OverrideDataType function to manually set the schema type and format for a specific Go type. This method has the highest precedence and is useful for fine-grained control over schema generation. ```go fizz.Generator().OverrideDataType(reflect.TypeOf(&UUIDv4{}), "string", "uuid") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.