### Go: OpenAPI 3.0 Multiple Examples Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md Shows how to define multiple examples for a parameter using the `WithExamples` option, associating each example with a summary and a value. ```Go parameter.StringParam("format", parameter.Query, parameter.WithExamples(map[string]parameter.Example{ "json": { Summary: "JSON format", Value: "json", }, "xml": { Summary: "XML format", Value: "xml", }, }), ) ``` -------------------------------- ### Go: Create String Parameter Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md Provides examples for creating string parameters using the `StringParam` function. It shows basic usage and how to configure various options like location, required status, description, example, pattern, and length constraints. ```Go // Basic string parameter parameter.StringParam("name", parameter.Query) // With options parameter.StringParam("name", parameter.Query, parameter.WithRequired(), parameter.WithDescription("User name"), parameter.WithExample("John Doe"), parameter.WithPattern("^[a-zA-Z ]+$"), parameter.WithMinLength(1), parameter.WithMaxLength(100), ) ``` -------------------------------- ### Install Swagno-Gin Source: https://github.com/go-swagno/swagno/blob/master/README.md Command to get the swagno-gin package. ```sh go get github.com/go-swagno/swagno-gin ``` -------------------------------- ### Create String Parameter (Go) Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Example of creating a string parameter with options for minimum/maximum length and a regular expression pattern. ```Go parameter.StrParam("name", parameter.Query, parameter.WithMinLen(2), parameter.WithMaxLen(50), parameter.WithPattern("^[a-zA-Z]+$"), ) ``` -------------------------------- ### Go Swagno Authentication Setup Source: https://github.com/go-swagno/swagno/blob/master/docs/04-examples-and-usage.md Demonstrates how to configure different authentication methods for Swagno, including Basic Auth, API Key Auth, and OAuth2, by setting authentication details on the Swagno instance. ```go // Basic Auth sw.SetBasicAuth("Basic authentication required") // API Key Auth sw.SetApiKeyAuth("X-API-Key", "header", "API key required for access") // OAuth2 Auth scopes := security.Scopes( security.Scope("read:products", "Read product data"), security.Scope("write:products", "Create and update products"), security.Scope("admin", "Administrative access"), ) sw.SetOAuth2Auth( "oauth2", "password", "", "http://localhost:8080/oauth/token", scopes, "OAuth2 authentication" ) ``` -------------------------------- ### Create Integer Parameter (Go) Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Example of creating an integer parameter with specific options like location, minimum, and maximum values. ```Go parameter.IntParam("id", parameter.Path, parameter.WithRequired(), parameter.WithMin(1), parameter.WithMax(1000), ) ``` -------------------------------- ### Creating Tags with Swagno Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md Provides examples of creating Tag objects using Swagno's `tag.New` function, including simple tags and tags with associated external documentation. ```go // Simple tag tag.New("users", "User operations") // Tag with external documentation tag.New("users", "User operations", tag.WithExternalDocs( "https://docs.example.com/users", "User API Documentation", ), ) ``` -------------------------------- ### Parse 'example' Struct Tag Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Utility function to parse the `example` tag from a struct field. It attempts to convert numeric values to uint64 and returns others as strings. ```go Name string `json:"name" example:"John Doe"` Age int `json:"age" example:"25"` ``` -------------------------------- ### Go: Create Float Parameter Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md Shows how to create float parameters using `FloatParam`. Examples include setting the name, location, description, example value, and defining minimum and maximum bounds. ```Go parameter.FloatParam("price", parameter.Query, parameter.WithDescription("Price filter"), parameter.WithExample(29.99), parameter.WithMin(0.0), parameter.WithMax(1000.0), ) ``` -------------------------------- ### Install Swagno-Fiber Source: https://github.com/go-swagno/swagno/blob/master/README.md Command to get the swagno-fiber package. ```sh go get github.com/go-swagno/swagno-fiber ``` -------------------------------- ### Complex Parameter Usage in Go Source: https://github.com/go-swagno/swagno/blob/master/docs/04-examples-and-usage.md Illustrates defining a GET endpoint for '/products' with various query parameters including string search, integer pagination, and an enum for sorting. It also shows a required header parameter for client version validation. ```go endpoint.New( endpoint.GET, "/products", endpoint.WithParams( // Query parameters parameter.StrParam("search", parameter.Query, parameter.WithDescription("Search term for products"), parameter.WithMinLen(2), parameter.WithMaxLen(100), ), parameter.IntParam("page", parameter.Query, parameter.WithDefault(1), parameter.WithMin(1), parameter.WithMax(1000), ), parameter.IntParam("limit", parameter.Query, parameter.WithDefault(10), parameter.WithMin(1), parameter.WithMax(100), ), // Enum parameter parameter.StrEnumParam("sort", parameter.Query, []string{"name", "price", "date"}, parameter.WithDefault("name"), ), // Header parameter parameter.StrParam("X-Client-Version", parameter.Header, parameter.WithRequired(), parameter.WithPattern("^\\d+\\.\\d+\\.\\d+$"), ), ), // ... other options ) ``` -------------------------------- ### Go Swagno v3 Basic API Example Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/00-documentation-summary.md This Go code snippet shows a practical example of using Swagno v3 to define a basic API endpoint for retrieving users, including path parameters, response definitions, and authentication. ```go openapi := swagno3.New(swagno3.Config{ Title: "User API", Version: "v1.0.0", }) openapi.AddServer("https://api.example.com/v1", "Production") openapi.SetBearerAuth("JWT", "Bearer authentication") endpoint := endpoint.New( endpoint.GET, "/users/{id}", endpoint.WithTags("users"), endpoint.WithParams( parameter.IntParam("id", parameter.Path, parameter.WithRequired(), parameter.WithExample(123), ), ), endpoint.WithSuccessfulReturns([]response.Response{ response.New(User{}, "200", "User found"), }), ) openapi.AddEndpoint(endpoint) ``` -------------------------------- ### Install Swagno Package Source: https://github.com/go-swagno/swagno/blob/master/README.md Command to get the swagno package using Go modules. ```sh go get github.com/go-swagno/swagno ``` -------------------------------- ### Swagger Export in Go Source: https://github.com/go-swagno/swagno/blob/master/docs/04-examples-and-usage.md Provides examples for exporting Swagger/OpenAPI definitions using Go Swagno. It covers getting the definition as a JSON string, saving it to a file, and handling potential errors during generation. ```go // Get as JSON string jsonDoc := sw.MustToJson() // Save to file sw.ExportSwaggerDocs("swagger.json") // With error handling jsonDoc, err := sw.ToJson() if err != nil { log.Fatal("Swagger generation failed:", err) } ``` -------------------------------- ### Go: Create Boolean Parameter Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md Illustrates the creation of boolean parameters using `BoolParam`. This covers setting the name, location, description, and an example value for the boolean field. ```Go parameter.BoolParam("active", parameter.Query, parameter.WithDescription("Filter by active status"), parameter.WithExample(true), ) ``` -------------------------------- ### Define Endpoint with Multiple Response Types Source: https://github.com/go-swagno/swagno/blob/master/docs/04-examples-and-usage.md Illustrates defining a GET endpoint for '/products/{id}' that can return different successful responses (Product or ProductWithReviews) and various error responses (400, 404, 500). ```go endpoint.New( endpoint.GET, "/products/{id}", endpoint.WithSuccessfulReturns([]response.Response{ response.New(Product{}, "200", "Product found"), response.New(ProductWithReviews{}, "200", "Product with reviews"), }), endpoint.WithErrors([]response.Response{ response.New(ErrorResponse{}, "400", "Invalid product ID"), response.New(ErrorResponse{}, "404", "Product not found"), response.New(ErrorResponse{}, "500", "Internal server error"), }), ) ``` -------------------------------- ### Go: Create Integer Parameter Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md Demonstrates creating integer parameters using `IntParam`. This includes specifying the name, location, and optional configurations such as required status, description, example, minimum, and maximum values. ```Go parameter.IntParam("id", parameter.Path, parameter.WithRequired(), parameter.WithDescription("User ID"), parameter.WithExample(123), parameter.WithMin(1), parameter.WithMax(999999), ) ``` -------------------------------- ### Go: Define Array and Multiple Examples Parameters (OpenAPI 3.0) Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/06-migration-guide.md Shows how to define array parameters with custom styles (e.g., 'form') and explode behavior, as well as string parameters supporting multiple examples in Swagno for OpenAPI 3.0. ```go parameter.ArrayParam("tags", parameter.Query, parameter.WithStyle("form"), // New: Parameter styles parameter.WithExplode(true), // New: Explode behavior parameter.WithDescription("Filter by tags"), ) ``` ```go parameter.StringParam("format", parameter.Query, parameter.WithExamples(map[string]parameter.Example{ "json": { Summary: "JSON format", Value: "json", }, "xml": { Summary: "XML format", Value: "xml", }, }), ) ``` -------------------------------- ### Example of Creating and Configuring a Tag Source: https://github.com/go-swagno/swagno/blob/master/docs/05-api-reference.md Shows how to create a new API tag with a name and description, and how to use the `WithExternalDocs` option to link to relevant external documentation. ```Go tag.New("users", "User management operations", tag.WithExternalDocs("User Guide", "https://docs.example.com/users"), ) ``` -------------------------------- ### Go Struct with OpenAPI Field Tags Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md An example of a Go struct demonstrating the use of various struct tags supported by Swagno for OpenAPI 3.0 field generation, including descriptions, examples, formats, and validations. ```go type User struct { ID int `json:"id" description:"User unique identifier" example:"123"` Name string `json:"name" description:"User full name" example:"John Doe" minLength:"1" maxLength:"100"` Email *string `json:"email,omitempty" description:"User email address" example:"john@example.com" format:"email"` Age int `json:"age" description:"User age" example:"30" minimum:"0" maximum:"150"` IsActive bool `json:"is_active" description:"Whether user is active" example:"true"` CreatedAt string `json:"created_at" description:"Creation timestamp" example:"2023-01-01T00:00:00Z" format:"date-time" readonly:"true"` Password string `json:"password" description:"User password" writeonly:"true"` Metadata map[string]interface{} `json:"metadata,omitempty" description:"Additional user metadata"` } ``` -------------------------------- ### Go Swagno: Response with Content Types Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md Demonstrates creating OpenAPI 3.0 responses with various content types like JSON and XML, including schema definitions and examples. It also shows how to add links to responses. ```go response.New(User{}, "200", "User found") response.NewWithContent("200", "User found", map[string]response.MediaType{ "application/json": { Schema: definition.SchemaFromStruct(User{}), Examples: map[string]response.Example{ "user": { Summary: "Example user", Value: User{ ID: 1, Name: "John Doe", Email: "john@example.com", }, }, }, }, "application/xml": { Schema: definition.SchemaFromStruct(User{}), }, }) response.New(User{}, "200", "User found") response.New(User{}, "201", "User created"). WithLinks(map[string]endpoint.Link{ "GetUser": endpoint.NewEnhancedLink(). SetOperationId("getUserById"). AddParameter("id", "$response.body#/id"), }) ``` -------------------------------- ### Create String Enum Parameter (Go) Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Example of creating a string enum parameter for a query parameter with a predefined list of string values. ```Go parameter.StrEnumParam("type", parameter.Query, []string{"user", "admin", "guest"}) ``` -------------------------------- ### Example Usage of Server with Variables in Go Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/02-core-modules.md This example demonstrates how to define a server with variables in the OpenAPI specification. It shows a server URL that can be customized using environment and version parameters, with default values and enumerations provided for the variables. ```go // Simple server openapi.AddServer("https://api.example.com", "Production server") // Server with variables (advanced usage) server := Server{ URL: "https://{environment}.example.com/{version}", Description: "Configurable server", Variables: map[string]ServerVariable{ "environment": { Default: "api", Enum: []string{"api", "staging", "dev"}, Description: "Environment name", }, "version": { Default: "v1", Description: "API version", }, }, } ``` -------------------------------- ### Define Endpoint with Security Source: https://github.com/go-swagno/swagno/blob/master/docs/04-examples-and-usage.md Demonstrates how to define a POST endpoint for '/admin/products' and specify security requirements using OAuth2 with an 'admin' scope or an API key. ```go endpoint.New( endpoint.POST, "/admin/products", endpoint.WithTags("admin", "products"), endpoint.WithSecurity([]map[string][]string{ {"oauth2": {"admin"}}, // OAuth2 admin scope required {"X-API-Key": {}}, // Or API key required }), // ... other options ) ``` -------------------------------- ### Set Endpoint Description and Summary Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Demonstrates how to set the description and summary for an API endpoint using `WithDescription` and `WithSummary` respectively. ```go endpoint.WithDescription("Get user details by ID") endpoint.WithSummary("Retrieve user information") ``` -------------------------------- ### Go createStructDefinitions Function Example Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Illustrates how `createStructDefinitions` handles various Go types, including slices, structs, pointers, maps, and interfaces, for Swagger definition generation. ```Go // []string, []int etc. Tags []string `json:"tags"` // []Struct types Sizes []Size `json:"sizes"` // []*Struct types SizePtrs []*Size `json:"size_ptrs"` // Special time handling SaleDate time.Time `json:"sale_date"` EndDate *time.Time `json:"end_date"` // Other struct types Complex ComplexModel `json:"complex"` // Pointer to struct CategoryId *uint64 `json:"category_id,omitempty"` // Map types generate special definitions Metadata map[string]interface{} `json:"metadata"` // interface{} types are marked as "Ambiguous Type" Data interface{} `json:"data"` ``` -------------------------------- ### Create Integer Enum Parameter (Go) Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Example of creating an integer enum parameter for a query parameter with a predefined list of integer values. ```Go parameter.IntEnumParam("status", parameter.Query, []int64{1, 2, 3}) ``` -------------------------------- ### Set Consume and Produce MIME Types (Go) Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Example of how to use the defined MIME types to specify the consume and produce types for an API endpoint. ```Go endpoint.WithConsume([]mime.MIME{mime.JSON, mime.URLFORM}) endpoint.WithProduce([]mime.MIME{mime.JSON, mime.XML}) ``` -------------------------------- ### Usage Example for Basic Authentication in Go Source: https://github.com/go-swagno/swagno/blob/master/docs/02-core-modules.md Demonstrates how to apply the `SetBasicAuth` method to configure basic authentication for the API. ```Go sw.SetBasicAuth("Basic auth for API access") ``` -------------------------------- ### Example Usage of Swagno Security Setup in Go Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/security-structure.md Demonstrates how to set up various security methods (Bearer, API Key, OAuth2) using Swagno v3 in Go, including configuring OAuth2 flows and applying security to endpoints. ```go import "github.com/go-swagno/swagno/v3/components/security" // Basic setup openapi := swagno3.New(swagno3.Config{Title: "My API", Version: "1.0.0"}) // Add Bearer auth openapi.SetBearerAuth("JWT", "Bearer authentication using JWT tokens") // Add API Key auth openapi.SetApiKeyAuth("X-API-Key", security.Header, "API key authentication") // Add OAuth2 with multiple flows flows := security.NewOAuthFlows(). WithAuthorizationCode( "https://example.com/oauth/authorize", "https://example.com/oauth/token", map[string]string{ "read": "Read access", "write": "Write access", }, ). WithClientCredentials( "https://example.com/oauth/token", map[string]string{ "api": "API access", }, ) openapi.SetOAuth2Auth(flows, "OAuth2 authentication") // Use in endpoints endpoint.New( endpoint.GET, "/protected", endpoint.WithSecurity([]map[security.SecuritySchemeName][]string{ {security.BearerAuth: {}}, {security.APIKeyAuth: {}}, {security.BasicAuth: {}}, {security.OpenIDConnect: {}}, {security.OAuth2: {"read", "write"}}, // Multiple scopes }), ) ``` -------------------------------- ### Go: Define Response Interface Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md Defines the Response interface, specifying methods to retrieve the response's description, return code, schema, headers, examples, and links. ```Go type Response interface { Description() string ReturnCode() string Schema() interface{} Headers() map[string]parameter.Parameter Examples() map[string]interface{} Links() map[string]endpoint.Link } ``` -------------------------------- ### Go: Define User Schema with Examples (OpenAPI 3.0) Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/06-migration-guide.md Shows the definition of a User struct in Go for OpenAPI 3.0 using Swagno, including field-level examples, descriptions, and format specifications like 'email'. Pointer types like `*string` are automatically handled as nullable. ```go type User struct { ID int `json:"id" example:"123" description:"User ID"` Name string `json:"name,omitempty" example:"John Doe" description:"User name"` Email *string `json:"email,omitempty" example:"john@example.com" format:"email" description:"User email"` // Note: *string automatically becomes nullable: true in OpenAPI 3.0 } ``` -------------------------------- ### Go Model Design Best Practices Source: https://github.com/go-swagno/swagno/blob/master/docs/04-examples-and-usage.md Illustrates good and bad practices for designing Go structs for API models. The 'good' example shows clear field definitions with JSON tags and examples, while the 'bad' example highlights the ambiguity of using `interface{}`. ```go // ✅ Good: Clear field definitions type User struct { ID uint64 `json:"id"` Name string `json:"name" example:"John Doe"` Email string `json:"email" example:"john@example.com"` IsActive *bool `json:"is_active,omitempty"` // Optional boolean Created time.Time `json:"created"` } // ❌ Bad: Ambiguous interface{} usage type BadUser struct { Data interface{} `json:"data"` // Appears as "Ambiguous Type" in Swagger } ``` -------------------------------- ### Integrate Swagno with Gin Framework in Go Source: https://github.com/go-swagno/swagno/blob/master/docs/04-examples-and-usage.md This Go code shows how to integrate Swagno with the Gin web framework. It defines API endpoints similarly to the Net/HTTP example but uses Gin's routing and middleware capabilities, serving Swagger UI via a wildcard route. ```go package main import ( "github.com/gin-gonic/gin" "github.com/go-swagno/swagno" "github.com/go-swagno/swagno-gin/swagger" "github.com/go-swagno/swagno/components/endpoint" "github.com/go-swagno/swagno/components/http/response" "github.com/go-swagno/swagno/components/mime" "github.com/go-swagno/swagno/components/parameter" "github.com/go-swagno/swagno/example/models" ) func main() { sw := swagno.New(swagno.Config{Title: "Testing API", Version: "v1.0.0"}) endpoints := []*endpoint.EndPoint{ endpoint.New( endpoint.GET, "/product", endpoint.WithTags("product"), endpoint.WithSuccessfulReturns([]response.Response{ response.New(models.Product{}, "200", "OK") }), endpoint.WithErrors([]response.Response{ response.New(models.UnsuccessfulResponse{}, "400", "Bad Request") }), endpoint.WithDescription("Get all products"), endpoint.WithProduce([]mime.MIME{mime.JSON, mime.XML}), endpoint.WithConsume([]mime.MIME{mime.JSON}), endpoint.WithSummary("Retrieve product list"), ), endpoint.New( endpoint.GET, "/product/{id}", endpoint.WithTags("product"), endpoint.WithParams( parameter.IntParam("id", parameter.Path, parameter.WithRequired()) ), endpoint.WithSuccessfulReturns([]response.Response{ response.New(models.SuccessfulResponse{}, "201", "Request Accepted") }), endpoint.WithErrors([]response.Response{ response.New(models.UnsuccessfulResponse{}, "400", "Bad Request") }), endpoint.WithProduce([]mime.MIME{mime.JSON, mime.XML}), ), } sw.AddEndpoints(endpoints) app := gin.Default() // Gin-specific swagger handler app.GET("/swagger/*any", swagger.SwaggerHandler(sw.MustToJson())) app.Run() } ``` -------------------------------- ### Example of Creating API Responses Source: https://github.com/go-swagno/swagno/blob/master/docs/05-api-reference.md Provides examples of how to use the `New` function to create different types of API responses, including single objects, lists of objects, and error responses. ```Go response.New(User{}, "200", "User retrieved successfully") response.New([]User{}, "200", "Users list") response.New(ErrorResponse{}, "404", "User not found") ``` -------------------------------- ### Using Security Schemes in Endpoints Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md Shows how to apply security schemes to specific API endpoints using Swagno. This includes examples for single, multiple (OR logic), and OAuth2 security schemes with scopes. ```go import "github.com/go-swagno/swagno/v3/components/security" // Single security scheme endpoint.WithSecurity([]map[security.SecuritySchemeName][]string{ {security.BearerAuth: {}}, }) // Multiple security schemes (OR) endpoint.WithSecurity([]map[security.SecuritySchemeName][]string{ {security.BearerAuth: {}}, {security.APIKeyAuth: {}}, }) // OAuth2 with scopes endpoint.WithSecurity([]map[security.SecuritySchemeName][]string{ {security.OAuth2: {"read", "write"}}, }) ``` -------------------------------- ### Define GET /products Endpoint in Go Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/04-examples-and-usage.md Defines a GET endpoint for retrieving products. It includes comprehensive query parameters for pagination, filtering (category, price range, stock status), and sorting, along with security definitions. ```go endpoint.New( endpoint.GET, "/products", endpoint.WithTags("products"), endpoint.WithSummary("List products"), endpoint.WithDescription("Retrieve products with advanced filtering and pagination"), endpoint.WithParams( // Pagination parameter.IntParam("page", parameter.Query, parameter.WithDefault(1), parameter.WithMin(1), parameter.WithExample(1), ), parameter.IntParam("limit", parameter.Query, parameter.WithDefault(20), parameter.WithMin(1), parameter.WithMax(100), ), // Filtering parameter.StringParam("category", parameter.Query, parameter.WithDescription("Filter by category slug"), parameter.WithExample("electronics"), ), parameter.FloatParam("min_price", parameter.Query, parameter.WithDescription("Minimum price filter"), parameter.WithMin(0), parameter.WithExample(10.00), ), parameter.FloatParam("max_price", parameter.Query, parameter.WithDescription("Maximum price filter"), parameter.WithMin(0), parameter.WithExample(1000.00), ), parameter.BoolParam("in_stock", parameter.Query, parameter.WithDescription("Filter by stock availability"), ), // Sorting parameter.StringParam("sort", parameter.Query, parameter.WithDescription("Sort field"), parameter.WithEnum([]interface{}{"name", "price", "created_at"}), parameter.WithDefault("name"), ), parameter.StringParam("order", parameter.Query, parameter.WithDescription("Sort order"), parameter.WithEnum([]interface{}{"asc", "desc"}), parameter.WithDefault("asc"), ), // Advanced array parameter parameter.ArrayParam("tags", parameter.Query, parameter.WithDescription("Filter by tags"), parameter.WithStyle("form"), parameter.WithExplode(true), parameter.WithItems(parameter.StringItems()), ), ), endpoint.WithSuccessfulReturns([]response.Response{ response.New([]Product{}, "200", "Products retrieved successfully"), }), endpoint.WithSecurity([]map[string][]string{ {"bearerAuth": {}}, {"apiKeyAuth": {}}, {"oauth2": {"read:products"}}, }), ) ``` -------------------------------- ### ComponentExample Struct Definition Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/02-core-modules.md Defines the ComponentExample structure used for providing examples within OpenAPI components. ```go type ComponentExample struct { Summary string `json:"summary,omitempty"` Description string `json:"description,omitempty"` Value interface{} `json:"value,omitempty"` ExternalValue string `json:"externalValue,omitempty"` } ``` -------------------------------- ### Create Response with Custom Content in Go Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/05-api-reference.md Explains how to create a response definition with custom content types and examples using `response.NewWithContent`. This allows specifying different media types like JSON or XML, along with their schemas and examples. ```Go resp := response.NewWithContent("200", "User found", map[string]response.MediaType{ "application/json": { Schema: definition.SchemaFromStruct(User{}), Examples: map[string]response.Example{ "user": { Summary: "Example user", Value: User{ID: 1, Name: "John"}, }, }, }, "application/xml": { Schema: definition.SchemaFromStruct(User{}), }, }) ``` -------------------------------- ### Create Custom HTTP Response Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Shows how to create a `CustomResponse` object using the `New` function, specifying the model, return code, and description for an HTTP response. ```go response.New(User{}, "200", "User found successfully") response.New([]User{}, "200", "Users retrieved") response.New(ErrorResponse{}, "404", "User not found") ``` -------------------------------- ### Go Swagno v3 Quick Start Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/00-documentation-summary.md This Go code snippet demonstrates how to initialize Swagno v3, add a server, set up bearer authentication, and generate OpenAPI documentation. ```go import swagno3 "github.com/go-swagno/swagno/v3" // Create OpenAPI instance openapi := swagno3.New(swagno3.Config{ Title: "My API", Version: "v1.0.0", }) // Add serveropenapi.AddServer("https://api.example.com/v1", "Production server") // Add securityopenapi.SetBearerAuth("JWT", "Bearer authentication") // Add endpointsopenapi.AddEndpoints(endpoints) // Generate documentation jsonDoc := openapi.MustToJson() ``` -------------------------------- ### Initialize Swagno v3 (OpenAPI 3.0) Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/06-migration-guide.md Initializes the Swagno v3 OpenAPI 3.0 client with basic configuration and adds server URLs. ```go openapi := swagno3.New(swagno3.Config{ Title: "My API", Version: "v1.0.0", Description: "API description", }) // Replace host + basePath with serversopenapi.AddServer("https://api.example.com/v1", "Production server")openapi.AddServer("https://staging.example.com/v1", "Staging server") ``` -------------------------------- ### Set Consume and Produce Content-Types Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Illustrates how to define the `Consumes` and `Produces` content types for an API endpoint using `WithConsume` and `WithProduce`. ```go endpoint.WithConsume([]mime.MIME{mime.JSON}) endpoint.WithProduce([]mime.MIME{mime.JSON, mime.XML}) ``` -------------------------------- ### Gin Framework Integration Example Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/04-examples-and-usage.md Demonstrates how to integrate Go Swagno with the Gin framework to create a web server. It includes setting up the Gin router, adding an OpenAPI documentation endpoint, and defining API routes. ```go package main import ( "net/http" "github.com/gin-gonic/gin" swagno3 "github.com/go-swagno/swagno/v3" ) func main() { // Create OpenAPI documentation openapi := createOpenAPIDoc() // Create Gin router r := gin.Default() // Add OpenAPI documentation endpoint r.GET("/openapi.json", func(c *gin.Context) { c.Header("Content-Type", "application/json") c.String(http.StatusOK, string(openapi.MustToJson())) }) // Add Swagger UI r.StaticFile("/docs", "./swagger-ui.html") // Add API routes api := r.Group("/api/v1") { api.GET("/users", getUsers) api.POST("/users", createUser) api.GET("/users/:id", getUserByID) api.PUT("/users/:id", updateUser) api.DELETE("/users/:id", deleteUser) } r.Run(":8080") } // Handler implementations... func getUsers(c *gin.Context) { /* implementation */ } func createUser(c *gin.Context) { /* implementation */ } func getUserByID(c *gin.Context) { /* implementation */ } func updateUser(c *gin.Context) { /* implementation */ } func deleteUser(c *gin.Context) { /* implementation */ } ``` -------------------------------- ### Integrate Swagno with Gin Source: https://github.com/go-swagno/swagno/blob/master/README.md Example of integrating Swagno with the Gin web framework using the swagno-gin swagger handler. ```go ... // assume you declare your endpoints and "sw"(swagno) instance a.GET("/swagger/*any", swagger.SwaggerHandler(sw.MustToJson())) ... ``` -------------------------------- ### Parameter Option Functions (Go) Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Lists available option functions for configuring API parameters, such as setting requirements, descriptions, default values, and validation rules. ```Go // WithRequired(): Required parameter // WithDescription(string): Description // WithDefault(interface{}): Default value // WithFormat(string): Format (e.g., "date-time") // WithMin(int64): Minimum value // WithMax(int64): Maximum value // WithMinLen(int64): Minimum length // WithMaxLen(int64): Maximum length // WithPattern(string): Regex pattern // WithMaxItems(int64): Max item count for arrays // WithMinItems(int64): Min item count for arrays // WithUniqueItems(bool): Should array items be unique // WithMultipleOf(int64): Number must be multiple of // WithCollectionFormat(CollectionFormat): Array format ("csv", "ssv", etc.) ``` -------------------------------- ### Define Header and Path Parameters with Swagno Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/04-examples-and-usage.md Illustrates the configuration of header and path parameters using Go Swagno. This includes setting descriptions, examples for header parameters, and patterns for path parameters to ensure valid input. ```go // Header parameter with examples parameter.StringParam("Accept-Language", parameter.Header, parameter.WithDescription("Preferred language"), parameter.WithExamples(map[string]parameter.Example{ "english": { Summary: "English", Value: "en-US", }, "spanish": { Summary: "Spanish", Value: "es-ES", }, "french": { Summary: "French", Value: "fr-FR", }, }), ) // Path parameter with pattern parameter.StringParam("slug", parameter.Path, parameter.WithRequired(), parameter.WithPattern("^[a-z0-9-]+$"), parameter.WithDescription("URL-friendly identifier"), parameter.WithExample("my-product-slug"), ) ``` -------------------------------- ### Define Security Requirements Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Shows how to define security requirements for an API endpoint using the `WithSecurity` option. ```go endpoint.WithSecurity([]map[string][]string{ {"apiKey": {}}, }) ``` -------------------------------- ### Create New Swagno Instance Source: https://github.com/go-swagno/swagno/blob/master/README.md Demonstrates how to create a new Swagno instance with basic configuration, including title and version. Optional properties like License and Info can also be provided. ```Go sw := swagno.New(swagno.Config{Title: "Testing API", Version: "v1.0.0", Host: "localhost:8080"}) // optionally you can also use the License and Info properties as well ``` -------------------------------- ### Bash: Install and Use OpenAPI Validator Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/06-migration-guide.md Installs the Swagger Parser tool globally using npm and then uses it to validate an OpenAPI JSON file. This helps ensure the generated documentation conforms to the OpenAPI specification. ```bash # Install OpenAPI validator npm install -g @apidevtools/swagger-parser # Validate your OpenAPI document swagger-parser validate openapi.json ``` -------------------------------- ### Define Response Interface Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Defines the `Response` interface for managing HTTP response structures, specifying methods for description and return code. ```go type Response interface { Description() string ReturnCode() string } ``` -------------------------------- ### Go Swagno Simple CRUD API Setup Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/04-examples-and-usage.md This Go code initializes Swagno to generate OpenAPI 3.0 documentation for a user management API. It configures the API title, version, summary, description, contact information, license, terms of service, and external documentation links. It also demonstrates adding multiple servers, security schemes (Bearer and API Key), and tags for organizing endpoints. ```go package main import ( "fmt" swagno3 "github.com/go-swagno/swagno/v3" "github.com/go-swagno/swagno/v3/components/endpoint" "github.com/go-swagno/swagno/v3/components/http/response" "github.com/go-swagno/swagno/v3/components/parameter" "github.com/go-swagno/swagno/v3/components/security" "github.com/go-swagno/swagno/v3/components/tag" ) // User model type User struct { ID uint64 `json:"id" example:"1" description:"User unique identifier" Name string `json:"name" example:"John Doe" description:"User full name" Email string `json:"email" example:"john@example.com" format:"email" description:"User email address" IsActive *bool `json:"is_active,omitempty" example:"true" description:"Whether user is active" } // CreateUserRequest model type CreateUserRequest struct { Name string `json:"name" example:"John Doe" minLength:"1" maxLength:"100" description:"User full name" Email string `json:"email" example:"john@example.com" format:"email" description:"User email address" } // ErrorResponse model type ErrorResponse struct { Error bool `json:"error" example:"true" description:"Indicates if this is an error" Message string `json:"message" example:"User not found" description:"Error message" Code string `json:"code,omitempty" example:"USER_NOT_FOUND" description:"Error code" } func main() { // Create OpenAPI 3.0 instance openapi := swagno3.New(swagno3.Config{ Title: "User Management API", Version: "v1.0.0", Summary: "A simple API for managing users", Description: "This API allows you to create, read, update, and delete users. It demonstrates OpenAPI 3.0.3 features with Swagno v3.", Contact: &swagno3.Contact{ Name: "API Support Team", Email: "support@example.com", URL: "https://example.com/support", }, License: &swagno3.License{ Name: "MIT", URL: "https://opensource.org/licenses/MIT", }, TermsOfService: "https://example.com/terms", ExternalDocs: swagno3.NewExternalDocs( "https://docs.example.com/api", "Complete API Documentation", ), }) // Add servers openapi.AddServer("https://api.example.com/v1", "Production server") openapi.AddServer("https://staging-api.example.com/v1", "Staging server") openapi.AddServer("http://localhost:8080/v1", "Development server") // Add security schemes openapi.SetBearerAuth("JWT", "Bearer authentication using JWT tokens") openapi.SetApiKeyAuth("X-API-Key", security.Header, "API key authentication") // Add tags openapi.AddTags( tag.New("users", "User management operations", tag.WithExternalDocs("https://docs.example.com/users", "User API docs"), ), tag.New("health", "Health check operations"), ) // Define endpoints endpoints := []*endpoint.EndPoint{ // GET /health - Health check endpoint.New( endpoint.GET, "/health", endpoint.WithTags("health"), endpoint.WithSummary("Health check"), endpoint.WithDescription("Check if the API is running"), endpoint.WithSuccessfulReturns([]response.Response{ response.New(map[string]string{"status": "ok"}, "200", "API is healthy"), }), ), // GET /users - List users endpoint.New( endpoint.GET, "/users", endpoint.WithTags("users"), endpoint.WithSummary("List users"), endpoint.WithDescription("Retrieve a paginated list of all users"), endpoint.WithParams( parameter.IntParam("page", parameter.Query, parameter.WithDescription("Page number for pagination"), parameter.WithDefault(1), parameter.WithMin(1), parameter.WithExample(1), ), parameter.IntParam("limit", parameter.Query, parameter.WithDescription("Number of users per page"), parameter.WithDefault(10), parameter.WithMin(1), parameter.WithMax(100), parameter.WithExample(10), ), parameter.StringParam("search", parameter.Query, parameter.WithDescription("Search users by name or email"), parameter.WithExample("john"), ), parameter.BoolParam("active", parameter.Query, parameter.WithDescription("Filter by active status"), parameter.WithExample(true), ), ), endpoint.WithSuccessfulReturns([]response.Response{ response.New([]User{}, "200", "List of users"), }), ``` -------------------------------- ### Basic, API Key, and OAuth Authentication Structs (Go) Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Structs provided by the Swagno library for defining different types of API authentication schemes. ```Go // BasicAuth, ApiKeyAuth, OAuth ``` -------------------------------- ### Create API Endpoint Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Demonstrates the creation of a new API endpoint using the `New` function. It shows how to specify the HTTP method, path, tags, parameters, and success/error responses. ```go endpoint.New( endpoint.GET, "/users/{id}", endpoint.WithTags("users"), endpoint.WithParams(parameter.IntParam("id", parameter.Path, parameter.WithRequired())), endpoint.WithSuccessfulReturns([]response.Response{response.New(User{}, "200", "OK")}), endpoint.WithErrors([]response.Response{response.New(ErrorResponse{}, "404", "Not Found")}), ) ``` -------------------------------- ### Go mergeEmbeddedStructFields Function Example Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Demonstrates how embedded struct fields are merged into the main struct's properties during definition generation. ```Go type EmbeddedStruct struct { Sizes // Embedded OtherField int `json:"other_field"` } // Embedded struct fields are moved to upper level. ``` -------------------------------- ### Setting Up Security Schemes in Go Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md Demonstrates how to configure different security schemes for OpenAPI documentation using Swagno. This includes basic, bearer, API key, OAuth2, and OpenID Connect authentication methods. ```go // Basic Authentication openapi.SetBasicAuth("Basic authentication required") // Bearer Authentication openapi.SetBearerAuth("JWT", "Bearer authentication using JWT tokens") // API Key Authentication openapi.SetApiKeyAuth("X-API-Key", security.Header, "API key authentication") openapi.SetApiKeyAuth("sessionId", security.Cookie, "Session ID authentication") // OAuth2 Authentication flows := security.NewOAuthFlows(). WithAuthorizationCode( "https://example.com/oauth/authorize", "https://example.com/oauth/token", map[string]string{ "read": "Read access", "write": "Write access", "delete": "Delete access", }, ). WithClientCredentials( "https://example.com/oauth/token", map[string]string{ "api": "API access", }, ) openapi.SetOAuth2Auth(flows, "OAuth2 with authorization code and client credentials") // OpenID Connect openapi.SetOpenIdConnectAuth( "https://example.example.com/.well-known/openid_configuration", "OpenID Connect authentication", ) ``` -------------------------------- ### Create Enhanced Schema Instance Source: https://github.com/go-swagno/swagno/blob/master/v3/docs/03-components-guide.md Demonstrates how to create an instance of EnhancedSchema, setting its summary and content media type, and configuring conditional logic using If, Then, and Else schemas. ```go // Create enhanced schema schema := definition.NewEnhancedSchema("object"). SetSummary("User information"). SetContentMediaType("application/json"). SetIfThenElse(ifSchema, thenSchema, elseSchema) ``` -------------------------------- ### Go MethodType Enum for API Endpoints Source: https://github.com/go-swagno/swagno/blob/master/docs/03-components-guide.md Defines the HTTP method types used for API endpoints, including GET, POST, PUT, DELETE, and others. ```Go type MethodType string const ( GET MethodType = "GET" POST MethodType = "POST" PUT MethodType = "PUT" DELETE MethodType = "DELETE" PATCH MethodType = "PATCH" OPTIONS MethodType = "OPTIONS" HEAD MethodType = "HEAD" ) ```