swagger

package
v0.260224.0 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MPL-2.0 Imports: 7 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithAuth

func WithAuth() func(*RouteConfig)

WithAuth marks the route as requiring authentication

func WithDeprecated

func WithDeprecated(message string) func(*RouteConfig)

WithDeprecated marks the route as deprecated

func WithDescription

func WithDescription(desc string) func(*RouteConfig)

WithDescription sets the route description

func WithErrorResponses

func WithErrorResponses(errors ...ErrorResponseConfig) func(*RouteConfig)

WithErrorResponses sets the error responses for swagger documentation

func WithMiddleware

func WithMiddleware(middleware ...gin.HandlerFunc) func(*RouteConfig)

WithMiddleware adds route-specific middleware

func WithQuery

func WithQuery(name, paramType, description string) func(*RouteConfig)

WithQuery adds a simple query parameter (optional by default)

func WithQueryConfig

func WithQueryConfig(name string, config QueryParamConfig) func(*RouteConfig)

WithQueryConfig adds a query parameter with full configuration

func WithQueryModel

func WithQueryModel(model interface{}, name ...string) func(*RouteConfig)

WithQueryModel sets a query model for swagger documentation Optional name parameter can be provided to specify an explicit model name for anonymous structs

func WithQueryModelName added in v0.260224.0

func WithQueryModelName(name string) func(*RouteConfig)

WithQueryModelName sets an explicit name for the query model (useful for anonymous structs)

func WithQueryRequired

func WithQueryRequired(name, paramType, description string) func(*RouteConfig)

WithQueryRequired adds a required query parameter

func WithRequestModel

func WithRequestModel(model interface{}, name ...string) func(*RouteConfig)

WithRequestModel sets the request model for swagger documentation Optional name parameter can be provided to specify an explicit model name for anonymous structs

func WithRequestModelName added in v0.260224.0

func WithRequestModelName(name string) func(*RouteConfig)

WithRequestModelName sets an explicit name for the request model (useful for anonymous structs)

func WithResponseModel

func WithResponseModel(model interface{}, name ...string) func(*RouteConfig)

WithResponseModel sets the response model for swagger documentation Optional name parameter can be provided to specify an explicit model name for anonymous structs

func WithResponseModelName added in v0.260224.0

func WithResponseModelName(name string) func(*RouteConfig)

WithResponseModelName sets an explicit name for the response model (useful for anonymous structs)

func WithTags

func WithTags(tags ...string) func(*RouteConfig)

WithTags sets the route tags for swagger grouping

Types

type ErrorResponseConfig

type ErrorResponseConfig struct {
	Code    int
	Message string
	Model   interface{}
}

ErrorResponseConfig defines error response configuration for swagger

type ExternalDocs

type ExternalDocs struct {
	Description string `json:"description,omitempty"`
	URL         string `json:"url"`
}

ExternalDocs represents external documentation object

type Handler

type Handler func(c *gin.Context)

Handler defines the interface for all API handlers

type Header struct {
	Description      string        `json:"description,omitempty"`
	Type             string        `json:"type"`
	Format           string        `json:"format,omitempty"`
	Items            *Items        `json:"items,omitempty"`
	CollectionFormat string        `json:"collectionFormat,omitempty"`
	Default          interface{}   `json:"default,omitempty"`
	Maximum          *float64      `json:"maximum,omitempty"`
	Minimum          *float64      `json:"minimum,omitempty"`
	MaxLength        *int          `json:"maxLength,omitempty"`
	MinLength        *int          `json:"minLength,omitempty"`
	Pattern          string        `json:"pattern,omitempty"`
	MaxItems         *int          `json:"maxItems,omitempty"`
	MinItems         *int          `json:"minItems,omitempty"`
	UniqueItems      bool          `json:"uniqueItems,omitempty"`
	Enum             []interface{} `json:"enum,omitempty"`
	MultipleOf       *float64      `json:"multipleOf,omitempty"`
}

Header represents a header object in Swagger

type Items

type Items struct {
	Type             string        `json:"type,omitempty"`
	Format           string        `json:"format,omitempty"`
	Items            *Items        `json:"items,omitempty"`
	CollectionFormat string        `json:"collectionFormat,omitempty"`
	Default          interface{}   `json:"default,omitempty"`
	Maximum          *float64      `json:"maximum,omitempty"`
	Minimum          *float64      `json:"minimum,omitempty"`
	MaxLength        *int          `json:"maxLength,omitempty"`
	MinLength        *int          `json:"minLength,omitempty"`
	Pattern          string        `json:"pattern,omitempty"`
	MaxItems         *int          `json:"maxItems,omitempty"`
	MinItems         *int          `json:"minItems,omitempty"`
	UniqueItems      bool          `json:"uniqueItems,omitempty"`
	Enum             []interface{} `json:"enum,omitempty"`
	MultipleOf       *float64      `json:"multipleOf,omitempty"`
}

Items represents items object for array parameters

type Operation

type Operation struct {
	Tags         []string              `json:"tags,omitempty"`
	Summary      string                `json:"summary,omitempty"`
	Description  string                `json:"description,omitempty"`
	ExternalDocs *ExternalDocs         `json:"externalDocs,omitempty"`
	OperationID  string                `json:"operationId,omitempty"`
	Consumes     []string              `json:"consumes,omitempty"`
	Produces     []string              `json:"produces,omitempty"`
	Parameters   []Parameter           `json:"parameters,omitempty"`
	Responses    map[string]Response   `json:"responses"`
	Schemes      []string              `json:"schemes,omitempty"`
	Deprecated   bool                  `json:"deprecated,omitempty"`
	Security     []map[string][]string `json:"security,omitempty"`
}

Operation represents an operation object in Swagger

type Parameter

type Parameter struct {
	Name             string        `json:"name"`
	In               string        `json:"in"` // "query", "header", "path", "formData", "body"
	Description      string        `json:"description,omitempty"`
	Required         bool          `json:"required"`
	Schema           *Schema       `json:"schema,omitempty"` // For body parameters
	Type             string        `json:"type,omitempty"`   // For non-body parameters
	Format           string        `json:"format,omitempty"`
	AllowEmptyValue  bool          `json:"allowEmptyValue,omitempty"`
	Items            *Items        `json:"items,omitempty"` // For array parameters
	CollectionFormat string        `json:"collectionFormat,omitempty"`
	Default          interface{}   `json:"default,omitempty"`
	Maximum          *float64      `json:"maximum,omitempty"`
	Minimum          *float64      `json:"minimum,omitempty"`
	MaxLength        *int          `json:"maxLength,omitempty"`
	MinLength        *int          `json:"minLength,omitempty"`
	Pattern          string        `json:"pattern,omitempty"`
	MaxItems         *int          `json:"maxItems,omitempty"`
	MinItems         *int          `json:"minItems,omitempty"`
	UniqueItems      bool          `json:"uniqueItems,omitempty"`
	Enum             []interface{} `json:"enum,omitempty"`
	MultipleOf       *float64      `json:"multipleOf,omitempty"`
}

Parameter represents a parameter object in Swagger

type PathItem

type PathItem struct {
	Get     *Operation `json:"get,omitempty"`
	Post    *Operation `json:"post,omitempty"`
	Put     *Operation `json:"put,omitempty"`
	Delete  *Operation `json:"delete,omitempty"`
	Patch   *Operation `json:"patch,omitempty"`
	Options *Operation `json:"options,omitempty"`
	Head    *Operation `json:"head,omitempty"`
}

PathItem represents a path item object in Swagger

type QueryParamConfig

type QueryParamConfig struct {
	Name        string
	Type        string
	Required    bool
	Default     interface{}
	Description string
	Enum        []interface{}
	Minimum     *int
	Maximum     *int
}

QueryParamConfig defines configuration for a single query parameter

type Response

type Response struct {
	Description string                 `json:"description"`
	Schema      *Schema                `json:"schema,omitempty"`
	Headers     map[string]Header      `json:"headers,omitempty"`
	Examples    map[string]interface{} `json:"examples,omitempty"`
}

Response represents a response object in Swagger

type RouteConfig

type RouteConfig struct {
	Method            string
	Path              string
	Handler           Handler
	Description       string
	Tags              []string
	AuthRequired      bool
	RequestModel      interface{} // For swagger documentation
	ResponseModel     interface{} // For swagger documentation
	RequestModelName  string      // Optional explicit name for anonymous request struct
	ResponseModelName string      // Optional explicit name for anonymous response struct
	ErrorResponses    []ErrorResponseConfig
	Middleware        []gin.HandlerFunc
	Deprecated        bool
	DeprecatedMsg     string
	QueryParams       []QueryParamConfig // Query parameters
	QueryModel        interface{}        // Query model for swagger documentation
	QueryModelName    string             // Optional explicit name for anonymous query struct
}

RouteConfig defines configuration for a single route

type RouteGroup

type RouteGroup struct {
	Router *gin.RouterGroup
	// contains filtered or unexported fields
}

RouteGroup manages a group of related routes

func (*RouteGroup) AddMiddleware

func (rg *RouteGroup) AddMiddleware(middleware ...gin.HandlerFunc)

AddMiddleware adds middleware to the route group

func (*RouteGroup) DELETE

func (rg *RouteGroup) DELETE(path string, handler Handler, options ...func(*RouteConfig))

DELETE is a shortcut for RegisterRoute with DELETE method

func (*RouteGroup) GET

func (rg *RouteGroup) GET(path string, handler Handler, options ...func(*RouteConfig))

GET is a shortcut for RegisterRoute with GET method

func (*RouteGroup) PATCH

func (rg *RouteGroup) PATCH(path string, handler Handler, options ...func(*RouteConfig))

PATCH is a shortcut for RegisterRoute with PATCH method

func (*RouteGroup) POST

func (rg *RouteGroup) POST(path string, handler Handler, options ...func(*RouteConfig))

POST is a shortcut for RegisterRoute with POST method

func (*RouteGroup) PUT

func (rg *RouteGroup) PUT(path string, handler Handler, options ...func(*RouteConfig))

PUT is a shortcut for RegisterRoute with PUT method

func (*RouteGroup) RegisterRoute

func (rg *RouteGroup) RegisterRoute(config RouteConfig)

RegisterRoute registers a single route

type RouteGroupOption

type RouteGroupOption func(*RouteGroup)

RouteGroupOption is a function that configures a RouteGroup

func GroupWithTags

func GroupWithTags(tags ...string) RouteGroupOption

GroupWithTags sets the tags for all routes in the group (unless overridden)

type RouteManager

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

RouteManager manages all route groups and swagger generation

Example
// Create gin engine
engine := gin.New()

// Create route manager
manager := NewRouteManager(engine)

// Set Swagger information
manager.SetSwaggerInfo(SwaggerInfo{
	Title:       "Group Routes API",
	Description: "A RESTful API built with Go Gin framework featuring route management, user operations, and Swagger documentation generation.",
	Version:     "1.0.0",
	Host:        "localhost:15000",
	BasePath:    "/",
	Contact: SwaggerContact{
		Name:  "API Support",
		Email: "support@example.com",
		URL:   "https://example.com/support",
	},
	License: SwaggerLicense{
		Name: "MIT",
		URL:  "https://opensource.org/licenses/MIT",
	},
})

// Create v1 group
v1 := manager.NewGroup("api", "v1", "")

// Register ping routes
v1.GET("/ping", PingHandler,
	WithDescription("Ping endpoint for connectivity check"),
	WithTags("ping"),
	WithResponseModel(struct {
		Message string `json:"message"`
	}{}),
)

// Register user routes
{
	// Create user
	v1.POST("/users", CreateUserHandler,
		WithDescription("Create a new user"),
		WithTags("users"),
		WithRequestModel(CreateUserRequest{}),
		WithResponseModel(User{}),
		WithErrorResponses(
			ErrorResponseConfig{
				Code:    400,
				Message: "Bad Request - Invalid input data",
				Model:   ErrorResponse{},
			},
			ErrorResponseConfig{
				Code:    409,
				Message: "Conflict - User already exists",
				Model:   ErrorResponse{},
			},
		),
	)
}

func NewRouteManager

func NewRouteManager(engine *gin.Engine) *RouteManager

NewRouteManager creates a new route manager

func (*RouteManager) AddGlobalMiddleware

func (rm *RouteManager) AddGlobalMiddleware(middleware ...gin.HandlerFunc)

AddGlobalMiddleware adds middleware to all routes

func (*RouteManager) GenerateSwaggerAnnotations

func (rm *RouteManager) GenerateSwaggerAnnotations() string

GenerateSwaggerAnnotations generates swagger annotations for all routes

func (*RouteManager) GenerateSwaggerJSON

func (rm *RouteManager) GenerateSwaggerJSON() (string, error)

GenerateSwaggerJSON generates the complete Swagger JSON specification

func (*RouteManager) GetEngine

func (rm *RouteManager) GetEngine() *gin.Engine

func (*RouteManager) GetRouteGroups

func (rm *RouteManager) GetRouteGroups() []*RouteGroup

GetRouteGroups returns all registered route groups

func (*RouteManager) NewGroup

func (rm *RouteManager) NewGroup(name, version, prefix string, opts ...RouteGroupOption) *RouteGroup

NewGroup creates a new route group

func (*RouteManager) RegisterSwaggerEndpoint

func (rm *RouteManager) RegisterSwaggerEndpoint(path string)

RegisterSwaggerEndpoint registers the swagger JSON endpoint

func (*RouteManager) SetSwaggerInfo

func (rm *RouteManager) SetSwaggerInfo(info SwaggerInfo)

SetSwaggerInfo sets the swagger information

func (*RouteManager) SetupSwaggerEndpoints

func (rm *RouteManager) SetupSwaggerEndpoints()

SetupSwaggerEndpoints configures Swagger documentation endpoints based on environment

type Schema

type Schema struct {
	Type                 string            `json:"type,omitempty"`
	Format               string            `json:"format,omitempty"`
	Title                string            `json:"title,omitempty"`
	Description          string            `json:"description,omitempty"`
	Default              interface{}       `json:"default,omitempty"`
	MultipleOf           *float64          `json:"multipleOf,omitempty"`
	Maximum              *float64          `json:"maximum,omitempty"`
	ExclusiveMaximum     bool              `json:"exclusiveMaximum,omitempty"`
	Minimum              *float64          `json:"minimum,omitempty"`
	ExclusiveMinimum     bool              `json:"exclusiveMinimum,omitempty"`
	MaxLength            *int              `json:"maxLength,omitempty"`
	MinLength            *int              `json:"minLength,omitempty"`
	Pattern              string            `json:"pattern,omitempty"`
	MaxItems             *int              `json:"maxItems,omitempty"`
	MinItems             *int              `json:"minItems,omitempty"`
	UniqueItems          bool              `json:"uniqueItems,omitempty"`
	Enum                 []interface{}     `json:"enum,omitempty"`
	Items                *Schema           `json:"items,omitempty"`
	AllOf                []Schema          `json:"allOf,omitempty"`
	Properties           map[string]Schema `json:"properties,omitempty"`
	AdditionalProperties *Schema           `json:"additionalProperties,omitempty"`
	ReadOnly             bool              `json:"readOnly,omitempty"`
	XML                  *XML              `json:"xml,omitempty"`
	ExternalDocs         *ExternalDocs     `json:"externalDocs,omitempty"`
	Example              interface{}       `json:"example,omitempty"`
	Required             []string          `json:"required,omitempty"`
	Ref                  string            `json:"$ref,omitempty"`
}

Schema represents a schema object in Swagger

type SecurityScheme

type SecurityScheme struct {
	Type             string            `json:"type"`
	Description      string            `json:"description,omitempty"`
	Name             string            `json:"name,omitempty"`
	In               string            `json:"in,omitempty"`   // "query", "header"
	Flow             string            `json:"flow,omitempty"` // "implicit", "password", "application", "accessCode"
	AuthorizationURL string            `json:"authorizationUrl,omitempty"`
	TokenURL         string            `json:"tokenUrl,omitempty"`
	Scopes           map[string]string `json:"scopes,omitempty"`
}

SecurityScheme represents a security scheme in Swagger

type Swagger

type Swagger struct {
	Swagger             string                    `json:"swagger"`
	Info                SwaggerInfoObject         `json:"info"`
	Host                string                    `json:"host,omitempty"`
	BasePath            string                    `json:"basePath,omitempty"`
	Schemes             []string                  `json:"schemes,omitempty"`
	Paths               map[string]PathItem       `json:"paths"`
	Definitions         map[string]Schema         `json:"definitions,omitempty"`
	SecurityDefinitions map[string]SecurityScheme `json:"securityDefinitions,omitempty"`
	Tags                []Tag                     `json:"tags,omitempty"`
	ExternalDocs        *ExternalDocs             `json:"externalDocs,omitempty"`
}

Swagger represents the complete Swagger specification

type SwaggerContact

type SwaggerContact struct {
	Name  string
	Email string
	URL   string
}

SwaggerContact holds contact information

type SwaggerContactObject

type SwaggerContactObject struct {
	Name  string `json:"name,omitempty"`
	Email string `json:"email,omitempty"`
	URL   string `json:"url,omitempty"`
}

SwaggerContactObject represents contact information

type SwaggerInfo

type SwaggerInfo struct {
	Title          string
	Description    string
	Version        string
	Host           string
	BasePath       string
	TermsOfService string
	Contact        SwaggerContact
	License        SwaggerLicense
}

SwaggerInfo holds information for swagger documentation

type SwaggerInfoObject

type SwaggerInfoObject struct {
	Title          string                `json:"title"`
	Description    string                `json:"description,omitempty"`
	TermsOfService string                `json:"termsOfService,omitempty"`
	Contact        *SwaggerContactObject `json:"contact,omitempty"`
	License        *SwaggerLicenseObject `json:"license,omitempty"`
	Version        string                `json:"version"`
}

SwaggerInfoObject represents the info object in Swagger

type SwaggerLicense

type SwaggerLicense struct {
	Name string
	URL  string
}

SwaggerLicense holds license information

type SwaggerLicenseObject

type SwaggerLicenseObject struct {
	Name string `json:"name,omitempty"`
	URL  string `json:"url,omitempty"`
}

SwaggerLicenseObject represents license information

type Tag

type Tag struct {
	Name         string        `json:"name"`
	Description  string        `json:"description,omitempty"`
	ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"`
}

Tag represents a tag object in Swagger

type XML

type XML struct {
	Name      string `json:"name,omitempty"`
	Namespace string `json:"namespace,omitempty"`
	Prefix    string `json:"prefix,omitempty"`
	Attribute bool   `json:"attribute,omitempty"`
	Wrapped   bool   `json:"wrapped,omitempty"`
}

XML represents XML object in Swagger

Jump to

Keyboard shortcuts

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