gindocs

package
v0.0.0-...-4d647cb Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Doc

func Doc(cfg DocConfig) gin.HandlerFunc

Doc returns a Gin middleware that registers inline documentation for a route.

func RefPath

func RefPath(name string) string

RefPath returns the OpenAPI $ref path for a named schema.

func TypeOf

func TypeOf(v interface{}) reflect.Type

TypeOf is a helper that returns the reflect.Type for a value, useful for registering types without creating instances.

Types

type AuthConfig

type AuthConfig struct {
	// Type is the authentication method.
	Type AuthType

	// Name is the header or query parameter name (for API key auth).
	Name string

	// In specifies where the API key is sent: "header" or "query" (for API key auth).
	In string

	// Scheme is the HTTP auth scheme (default: "bearer" for Bearer auth).
	Scheme string

	// BearerFormat describes the bearer token format (e.g., "JWT").
	BearerFormat string
}

AuthConfig configures authentication for the "Try It" feature.

type AuthType

type AuthType int

AuthType represents the authentication method for "Try It" functionality.

const (
	// AuthNone disables authentication in the UI.
	AuthNone AuthType = iota
	// AuthBearer enables Bearer token authentication.
	AuthBearer
	// AuthAPIKey enables API key authentication.
	AuthAPIKey
	// AuthBasic enables Basic authentication.
	AuthBasic
)

type ComponentsObject

type ComponentsObject struct {
	Schemas         map[string]*SchemaObject         `json:"schemas,omitempty"`
	SecuritySchemes map[string]*SecuritySchemeObject `json:"securitySchemes,omitempty"`
	Parameters      map[string]*ParameterObject      `json:"parameters,omitempty"`
	RequestBodies   map[string]*RequestBodyObject    `json:"requestBodies,omitempty"`
	Responses       map[string]*Response             `json:"responses,omitempty"`
}

ComponentsObject holds reusable components.

type Config

type Config struct {
	// Prefix is the URL prefix for docs endpoints (default: "/docs").
	Prefix string

	// Title is the API title shown in the docs (default: auto-detect from module name).
	Title string

	// Description is the API description.
	Description string

	// Version is the API version (default: "1.0.0").
	Version string

	// UI selects the documentation UI: UIScalar (default) or UISwagger.
	UI UIType

	// ScalarTheme sets the Scalar UI theme (default: "kepler").
	// Options: alternate, default, moon, purple, solarized, bluePlanet,
	// saturn, kepler, mars, deepSpace, laserwave.
	ScalarTheme string

	// DevMode re-introspects routes on every request when true.
	// Defaults to auto-detection from GIN_MODE.
	DevMode bool

	// ReadOnly disables "Try It" functionality when true.
	ReadOnly bool

	// Auth configures authentication for "Try It" requests.
	Auth AuthConfig

	// Servers lists API server URLs for "Try It" requests.
	Servers []ServerInfo

	// Contact holds API contact information.
	Contact ContactInfo

	// License holds API license information.
	License LicenseInfo

	Logo string

	// ExcludeRoutes is a list of glob patterns for routes to exclude from docs.
	ExcludeRoutes []string

	// ExcludePrefixes is a list of path prefixes for routes to exclude from docs.
	ExcludePrefixes []string

	// Models is a list of GORM model instances to register as schemas.
	Models []interface{}

	// CustomSections adds extra documentation sections rendered as markdown.
	CustomSections []Section

	// CustomCSS is custom CSS injected into the documentation UI.
	CustomCSS string
}

Config holds all configuration for Gin Docs.

type ContactInfo

type ContactInfo struct {
	// Name is the contact name.
	Name string

	// URL is the contact URL.
	URL string

	// Email is the contact email.
	Email string
}

ContactInfo holds API contact information.

type ContactObject

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

ContactObject holds contact information.

type DocConfig

type DocConfig struct {
	// Summary is the operation summary.
	Summary string
	// Description is the operation description.
	Description string
	// Tags are the operation tags.
	Tags []string
	// RequestBody is the request body type (pass a struct instance).
	RequestBody interface{}
	// Response is the response body type (pass a struct instance).
	Response interface{}
	// ResponseCode is the primary success status code.
	ResponseCode int
	// Deprecated marks the operation as deprecated.
	Deprecated bool
}

DocConfig holds inline documentation configuration for the Doc() middleware.

type ExternalDocsObject

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

ExternalDocsObject describes external documentation.

type GinDocs

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

GinDocs is the core engine that orchestrates route introspection, schema generation, and OpenAPI spec assembly.

func Mount

func Mount(router *gin.Engine, db *gorm.DB, configs ...Config) *GinDocs

Mount registers Gin Docs routes on the given router. db is optional — pass nil if not using GORM models. configs is variadic — pass zero or one Config.

func (*GinDocs) Group

func (gd *GinDocs) Group(pattern string) *GroupOverride

Group returns a GroupOverride builder for routes matching the given pattern.

func (*GinDocs) Route

func (gd *GinDocs) Route(key string) *RouteOverride

Route returns a RouteOverride builder for the specified "METHOD /path" key.

type GroupOverride

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

GroupOverride holds documentation overrides for a route group.

func (*GroupOverride) Security

func (g *GroupOverride) Security(schemes ...string) *GroupOverride

Security sets security scheme names for all routes in the group.

func (*GroupOverride) Tags

func (g *GroupOverride) Tags(tags ...string) *GroupOverride

Tags sets the tags for all routes in the group.

type Header struct {
	Description string        `json:"description,omitempty"`
	Schema      *SchemaObject `json:"schema,omitempty"`
}

Header describes a response header.

type InfoObject

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

InfoObject provides metadata about the API.

type InsomniaExport

type InsomniaExport struct {
	Type      string             `json:"_type"`
	Format    int                `json:"__export_format"`
	Source    string             `json:"__export_source"`
	Resources []InsomniaResource `json:"resources"`
}

InsomniaExport represents an Insomnia v4 export.

type InsomniaHeader

type InsomniaHeader struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

InsomniaHeader represents a header in an Insomnia request.

type InsomniaResource

type InsomniaResource struct {
	ID          string           `json:"_id"`
	Type        string           `json:"_type"`
	ParentID    string           `json:"parentId,omitempty"`
	Name        string           `json:"name"`
	Description string           `json:"description,omitempty"`
	URL         string           `json:"url,omitempty"`
	Method      string           `json:"method,omitempty"`
	Body        interface{}      `json:"body,omitempty"`
	Headers     []InsomniaHeader `json:"headers,omitempty"`
}

InsomniaResource represents a resource in an Insomnia export.

type LicenseInfo

type LicenseInfo struct {
	// Name is the license name (e.g., "MIT").
	Name string

	// URL is the license URL.
	URL string
}

LicenseInfo holds API license information.

type LicenseObject

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

LicenseObject holds license information.

type MediaType

type MediaType struct {
	Schema  *SchemaObject `json:"schema,omitempty"`
	Example interface{}   `json:"example,omitempty"`
}

MediaType describes a media type with a schema and examples.

type OpenAPISpec

type OpenAPISpec struct {
	OpenAPI      string                `json:"openapi"`
	Info         InfoObject            `json:"info"`
	Servers      []ServerObject        `json:"servers,omitempty"`
	Paths        map[string]*PathItem  `json:"paths"`
	Components   *ComponentsObject     `json:"components,omitempty"`
	Security     []SecurityRequirement `json:"security,omitempty"`
	Tags         []TagObject           `json:"tags,omitempty"`
	ExternalDocs *ExternalDocsObject   `json:"externalDocs,omitempty"`
}

OpenAPISpec represents a complete OpenAPI 3.1 specification.

type OperationObject

type OperationObject struct {
	Tags         []string              `json:"tags,omitempty"`
	Summary      string                `json:"summary,omitempty"`
	Description  string                `json:"description,omitempty"`
	OperationID  string                `json:"operationId,omitempty"`
	Parameters   []ParameterObject     `json:"parameters,omitempty"`
	RequestBody  *RequestBodyObject    `json:"requestBody,omitempty"`
	Responses    map[string]*Response  `json:"responses"`
	Security     []SecurityRequirement `json:"security,omitempty"`
	Deprecated   bool                  `json:"deprecated,omitempty"`
	ExternalDocs *ExternalDocsObject   `json:"externalDocs,omitempty"`
}

OperationObject describes a single API operation on a path.

type ParameterObject

type ParameterObject struct {
	Name        string        `json:"name"`
	In          string        `json:"in"` // "query", "header", "path", "cookie"
	Description string        `json:"description,omitempty"`
	Required    bool          `json:"required,omitempty"`
	Deprecated  bool          `json:"deprecated,omitempty"`
	Schema      *SchemaObject `json:"schema,omitempty"`
	Example     interface{}   `json:"example,omitempty"`
}

ParameterObject describes a single operation parameter.

type PathItem

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

PathItem describes operations available on a single path.

func (*PathItem) SetOperation

func (p *PathItem) SetOperation(method string, op *OperationObject)

SetOperation sets the operation for the given HTTP method on the path item.

type PostmanBody

type PostmanBody struct {
	Mode    string              `json:"mode"`
	Raw     string              `json:"raw,omitempty"`
	Options *PostmanBodyOptions `json:"options,omitempty"`
}

PostmanBody represents a request body.

type PostmanBodyOptions

type PostmanBodyOptions struct {
	Raw PostmanRawOptions `json:"raw"`
}

PostmanBodyOptions holds body format options.

type PostmanCollection

type PostmanCollection struct {
	Info PostmanInfo   `json:"info"`
	Item []PostmanItem `json:"item"`
}

PostmanCollection represents a Postman v2.1 collection.

type PostmanHeader

type PostmanHeader struct {
	Key   string `json:"key"`
	Value string `json:"value"`
	Type  string `json:"type"`
}

PostmanHeader represents a request header.

type PostmanInfo

type PostmanInfo struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Schema      string `json:"schema"`
}

PostmanInfo holds collection metadata.

type PostmanItem

type PostmanItem struct {
	Name    string          `json:"name"`
	Item    []PostmanItem   `json:"item,omitempty"`
	Request *PostmanRequest `json:"request,omitempty"`
}

PostmanItem represents a folder or request in a Postman collection.

type PostmanRawOptions

type PostmanRawOptions struct {
	Language string `json:"language"`
}

PostmanRawOptions holds raw body language setting.

type PostmanRequest

type PostmanRequest struct {
	Method      string          `json:"method"`
	Header      []PostmanHeader `json:"header,omitempty"`
	Body        *PostmanBody    `json:"body,omitempty"`
	URL         PostmanURL      `json:"url"`
	Description string          `json:"description,omitempty"`
}

PostmanRequest represents a Postman request.

type PostmanURL

type PostmanURL struct {
	Raw      string   `json:"raw"`
	Protocol string   `json:"protocol,omitempty"`
	Host     []string `json:"host,omitempty"`
	Path     []string `json:"path,omitempty"`
}

PostmanURL represents a Postman URL.

type RelType

type RelType int

RelType represents the type of a GORM relationship.

const (
	// RelHasOne represents a has-one relationship.
	RelHasOne RelType = iota
	// RelHasMany represents a has-many relationship.
	RelHasMany
	// RelBelongsTo represents a belongs-to relationship.
	RelBelongsTo
	// RelMany2Many represents a many-to-many relationship.
	RelMany2Many
)

type RelationshipInfo

type RelationshipInfo struct {
	// FieldName is the struct field name.
	FieldName string
	// Type is the relationship type.
	Type RelType
	// RelatedModel is the name of the related model.
	RelatedModel string
}

RelationshipInfo describes a detected GORM relationship.

type RequestBodyObject

type RequestBodyObject struct {
	Description string               `json:"description,omitempty"`
	Content     map[string]MediaType `json:"content"`
	Required    bool                 `json:"required,omitempty"`
}

RequestBodyObject describes a request body.

type Response

type Response struct {
	Description string               `json:"description"`
	Content     map[string]MediaType `json:"content,omitempty"`
	Headers     map[string]*Header   `json:"headers,omitempty"`
}

Response describes a single response from an API operation.

type RouteMetadata

type RouteMetadata struct {
	// Method is the HTTP method (GET, POST, PUT, PATCH, DELETE, etc.).
	Method string

	// Path is the Gin route path (e.g., "/api/users/:id").
	Path string

	// OpenAPIPath is the path converted to OpenAPI format (e.g., "/api/users/{id}").
	OpenAPIPath string

	// HandlerName is the fully qualified handler function name.
	HandlerName string

	// PathParams lists path parameter names extracted from the route.
	PathParams []string

	// Tags are auto-detected operation tags (from route groups).
	Tags []string
}

RouteMetadata holds parsed information about a single route.

type RouteOverride

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

RouteOverride holds documentation overrides for a specific route.

func (*RouteOverride) Deprecated

func (r *RouteOverride) Deprecated(d bool) *RouteOverride

Deprecated marks the operation as deprecated.

func (*RouteOverride) Description

func (r *RouteOverride) Description(d string) *RouteOverride

Description sets the operation description.

func (*RouteOverride) RequestBody

func (r *RouteOverride) RequestBody(v interface{}) *RouteOverride

RequestBody registers the request body type for this route.

func (*RouteOverride) Response

func (r *RouteOverride) Response(statusCode int, body interface{}, description string) *RouteOverride

Response registers a response for this route.

func (*RouteOverride) Security

func (r *RouteOverride) Security(schemes ...string) *RouteOverride

Security sets security scheme names for this route.

func (*RouteOverride) Summary

func (r *RouteOverride) Summary(s string) *RouteOverride

Summary sets the operation summary.

func (*RouteOverride) Tags

func (r *RouteOverride) Tags(tags ...string) *RouteOverride

Tags sets the operation tags.

type SchemaObject

type SchemaObject struct {
	// Reference
	Ref string `json:"$ref,omitempty"`

	// Type
	Type   string `json:"type,omitempty"`
	Format string `json:"format,omitempty"`

	// Metadata
	Title       string      `json:"title,omitempty"`
	Description string      `json:"description,omitempty"`
	Default     interface{} `json:"default,omitempty"`
	Example     interface{} `json:"example,omitempty"`
	Deprecated  bool        `json:"deprecated,omitempty"`
	ReadOnly    bool        `json:"readOnly,omitempty"`
	WriteOnly   bool        `json:"writeOnly,omitempty"`
	Nullable    bool        `json:"nullable,omitempty"`

	// Validation — numbers
	Minimum          *float64 `json:"minimum,omitempty"`
	Maximum          *float64 `json:"maximum,omitempty"`
	ExclusiveMinimum *float64 `json:"exclusiveMinimum,omitempty"`
	ExclusiveMaximum *float64 `json:"exclusiveMaximum,omitempty"`
	MultipleOf       *float64 `json:"multipleOf,omitempty"`

	// Validation — strings
	MinLength *int   `json:"minLength,omitempty"`
	MaxLength *int   `json:"maxLength,omitempty"`
	Pattern   string `json:"pattern,omitempty"`

	// Validation — arrays
	Items    *SchemaObject `json:"items,omitempty"`
	MinItems *int          `json:"minItems,omitempty"`
	MaxItems *int          `json:"maxItems,omitempty"`

	// Validation — objects
	Properties           map[string]*SchemaObject `json:"properties,omitempty"`
	Required             []string                 `json:"required,omitempty"`
	AdditionalProperties *SchemaObject            `json:"additionalProperties,omitempty"`

	// Enum
	Enum []interface{} `json:"enum,omitempty"`

	// Composition
	AllOf []*SchemaObject `json:"allOf,omitempty"`
	OneOf []*SchemaObject `json:"oneOf,omitempty"`
	AnyOf []*SchemaObject `json:"anyOf,omitempty"`
}

SchemaObject represents a JSON Schema object (OpenAPI 3.1 compatible).

func SchemaFromType

func SchemaFromType(v interface{}, registry *TypeRegistry) *SchemaObject

SchemaFromType generates an OpenAPI schema for a Go value and registers it.

func SchemaRef

func SchemaRef(name string) *SchemaObject

SchemaRef returns a SchemaObject that is a $ref to a named component.

type Section

type Section struct {
	// Title is the section heading.
	Title string

	// Content is the section body in markdown.
	Content string
}

Section represents a custom documentation section.

type SecurityRequirement

type SecurityRequirement map[string][]string

SecurityRequirement maps security scheme names to required scopes.

type SecuritySchemeObject

type SecuritySchemeObject struct {
	Type         string `json:"type"`
	Description  string `json:"description,omitempty"`
	Name         string `json:"name,omitempty"`   // for apiKey
	In           string `json:"in,omitempty"`     // for apiKey: "header", "query", "cookie"
	Scheme       string `json:"scheme,omitempty"` // for http: "bearer", "basic"
	BearerFormat string `json:"bearerFormat,omitempty"`
}

SecuritySchemeObject defines a security scheme.

type ServerInfo

type ServerInfo struct {
	// URL is the server URL.
	URL string

	// Description describes this server.
	Description string
}

ServerInfo describes an API server.

type ServerObject

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

ServerObject describes a server.

type TagInfo

type TagInfo struct {
	// JSON tag
	JSONName  string
	OmitEmpty bool
	JSONSkip  bool

	// Binding/validate tag
	Required    bool
	MinLength   *int
	MaxLength   *int
	Minimum     *float64
	Maximum     *float64
	Enum        []string
	Format      string // e.g., "email", "uri", "uuid"
	Pattern     string
	BindingSkip bool

	// GORM tag
	PrimaryKey     bool
	AutoCreateTime bool
	AutoUpdateTime bool
	GORMSize       *int
	GORMDefault    *string
	UniqueIndex    bool
	GORMSkip       bool
	GORMType       string

	// Docs tag
	Description string
	Example     string
	Deprecated  bool
	Hidden      bool
	DocsFormat  string
	DocsEnum    []string
}

TagInfo holds parsed information from struct field tags.

type TagObject

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

TagObject describes a tag used for API operation grouping.

type TypeRegistry

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

TypeRegistry manages schema deduplication and $ref generation.

func (*TypeRegistry) All

func (r *TypeRegistry) All() map[string]*SchemaObject

All returns a copy of all registered schemas.

func (*TypeRegistry) Get

func (r *TypeRegistry) Get(name string) (*SchemaObject, bool)

Get retrieves a schema by name.

func (*TypeRegistry) Has

func (r *TypeRegistry) Has(name string) bool

Has checks if a schema with the given name exists.

func (*TypeRegistry) Register

func (r *TypeRegistry) Register(name string, schema *SchemaObject)

Register adds a schema to the registry under the given name.

type UIType

type UIType int

UIType represents the documentation UI to serve.

const (
	// UISwagger serves the Swagger UI (default).
	UISwagger UIType = iota
	// UIScalar serves the Scalar UI.
	UIScalar
)

Jump to

Keyboard shortcuts

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