core

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrSecurityTypeRequired             = fmt.Errorf("security scheme type is required")
	ErrSecurityHTTPSchemeRequired       = fmt.Errorf("http security scheme requires 'scheme' field")
	ErrSecurityAPIKeyNameRequired       = fmt.Errorf("apiKey security scheme requires 'name' field")
	ErrSecurityAPIKeyInRequired         = fmt.Errorf("apiKey security scheme requires 'in' field")
	ErrSecurityAPIKeyInInvalid          = fmt.Errorf("apiKey 'in' must be one of: header, query, cookie")
	ErrSecurityOAuth2FlowsRequired      = fmt.Errorf("oauth2 security scheme requires 'flows'")
	ErrSecurityOpenIDConnectURLRequired = fmt.Errorf("openIdConnect security scheme requires 'openIdConnectUrl'")
	ErrSecurityTypeInvalid              = fmt.Errorf("invalid security scheme type")
)

Custom errors for validation

Functions

func ErrDuplicatePath

func ErrDuplicatePath(path string, method string) error

ErrDuplicatePath returns error for duplicate path+method combination

func ErrEmptyTypeName

func ErrEmptyTypeName(typePath string) error

ErrEmptyTypeName returns error for types with empty name

func ErrInvalidPath

func ErrInvalidPath(path string, reason string) error

ErrInvalidPath returns error for invalid path

func ErrParameterNotFound

func ErrParameterNotFound(paramName string, paramType string) error

ErrParameterNotFound returns error for missing parameter

func ErrSecuritySchemeNotFound

func ErrSecuritySchemeNotFound(name string) error

ErrSecuritySchemeNotFound returns error for missing security scheme

func ErrTypeNameCollision

func ErrTypeNameCollision(typeName string, types []string) error

ErrTypeNameCollision returns error for type name collisions

func ExtractRequestTypeFromHandler

func ExtractRequestTypeFromHandler(handler any) (reflect.Type, error)

ExtractRequestTypeFromHandler extracts the request type from a handler function signature Expected signature: func(ctx ReqContext[*gin.Context, Req]) (Resp, error)

func GetEndpointRegistry

func GetEndpointRegistry() *registryStore

func GetHandlerName

func GetHandlerName(handler any) string

GetHandlerName extracts the name of a handler function

func ValidateSecurityRequirement

func ValidateSecurityRequirement(schemeNames []string, schemes SecuritySchemes) error

ValidateSecurityRequirement checks if a security requirement references valid schemes

Types

type Components

type Components struct {
	Schemas         map[string]*Schema
	SecuritySchemes SecuritySchemes
	Parameters      map[string]*Parameter
	RequestBodies   map[string]*RequestBody
	Responses       map[string]*Response
	Headers         map[string]*Header
}

Components holds reusable definitions

type Contact

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

Contact represents contact information

type EndpointSpec

type EndpointSpec struct {
	Method      string `json:"method" yaml:"method"`
	Path        string `json:"path" yaml:"path"`
	ContentType string `json:"content" yaml:"content"`
	Security    string `json:"security"` // References a security scheme name in SecuritySchemes
	Summary     string `json:"summary,omitempty" yaml:"summary,omitempty"`
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
	OperationID string `json:"operationId,omitempty" yaml:"operationId,omitempty"`
	Responses   []ResponseSpec
	Tags        []string
}

type FieldInfo

type FieldInfo struct {
	Name     string
	Type     reflect.Type
	Location FieldLocation
	JSONTag  string
}

FieldInfo represents metadata about a single field

type FieldLocation

type FieldLocation string

FieldLocation represents where a field comes from (path, query, header, body)

const (
	LocationPath   FieldLocation = "path"
	LocationQuery  FieldLocation = "query"
	LocationHeader FieldLocation = "header"
	LocationBody   FieldLocation = "body"
)
type Header struct {
	Description string
	Schema      *Schema
	Required    bool
}

Header represents a response header

type Info

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

Info represents the OpenAPI info object

type License

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

License represents license information

type MediaType

type MediaType struct {
	Schema   *SchemaRef
	Example  interface{}
	Examples map[string]interface{}
}

MediaType represents content with schema

type OAuthFlow

type OAuthFlow struct {
	AuthorizationURL string            `json:"authorizationUrl,omitempty"`
	TokenURL         string            `json:"tokenUrl,omitempty"`
	RefreshURL       string            `json:"refreshUrl,omitempty"`
	Scopes           map[string]string `json:"scopes"`
}

OAuthFlow represents a single OAuth2 flow

type OAuthFlows

type OAuthFlows struct {
	Implicit          *OAuthFlow `json:"implicit,omitempty"`
	Password          *OAuthFlow `json:"password,omitempty"`
	ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty"`
	AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty"`
}

OAuthFlows represents OAuth2 flows

type Operation

type Operation struct {
	Summary     string
	Description string
	OperationID string
	Tags        []string
	Parameters  []*Parameter
	RequestBody *RequestBody
	Responses   map[string]*Response
	Security    []SecurityRequirement
	Deprecated  bool
}

Operation represents an API operation

type Par

type Par[Out any] struct {
	Name string
	Pipe PipeFn[Out]
	Type string
}

Par defines a named parameter with a parsing pipeline

type Parameter

type Parameter struct {
	Name        string
	In          string // path, query, header, cookie
	Description string
	Required    bool
	Deprecated  bool
	Schema      *Schema
}

Parameter represents a request parameter

type PathItem

type PathItem struct {
	Summary     string
	Description string
	Get         *Operation
	Post        *Operation
	Put         *Operation
	Patch       *Operation
	Delete      *Operation
	Head        *Operation
	Options     *Operation
	Parameters  []*Parameter
}

PathItem represents a path with operations

type PipeFn

type PipeFn[Out any] func(string) (Out, error)

PipeFn transforms input of type In to output of type Out

type RegisteredEndpoint

type RegisteredEndpoint struct {
	Method       string
	Path         string
	Summary      string
	Description  string
	OperationID  string
	Tags         []string
	Security     string // References a security scheme name in SecuritySchemes
	ContentType  string
	RequestInfo  *RequestStructInfo
	RequestType  reflect.Type
	ResponseType reflect.Type
	Responses    []ResponseSpec
	HandlerName  string // Name of the handler function for documentation
}

RegisteredEndpoint holds information about a registered endpoint for OpenAPI generation

type RequestBody

type RequestBody struct {
	Description string
	Required    bool
	Content     map[string]*MediaType
}

RequestBody represents a request body

type RequestStructInfo

type RequestStructInfo struct {
	Type   reflect.Type
	Fields map[FieldLocation][]*FieldInfo
}

RequestStructInfo represents the structure of a request type

func AnalyzePlainRequestStructure

func AnalyzePlainRequestStructure(requestType reflect.Type) (*RequestStructInfo, error)

func AnalyzeRequestStructure

func AnalyzeRequestStructure(requestType reflect.Type) (*RequestStructInfo, error)

AnalyzeRequestStructure analyzes the request type to extract field information It looks for nested structs with 'gas' tags and extracts their fields with 'in' tags

type Response

type Response struct {
	Description string
	Content     map[string]*MediaType
	Headers     map[string]*Header
}

Response represents a response

type ResponseShortSpec

type ResponseShortSpec struct {
	StatusCode  int
	Description string
	ContentType string
	Model       any
}

type ResponseSpec

type ResponseSpec struct {
	StatusCode  int
	Description string
	ContentType string
	Model       any
}

type Schema

type Schema struct {
	Type        string `json:"type,omitempty"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	Format      string `json:"format,omitempty"`
	Default     any    `json:"default,omitempty"`
	Example     any    `json:"example,omitempty"`

	// Object properties
	Properties           map[string]*SchemaRef `json:"properties,omitempty"`
	Required             []string              `json:"required,omitempty"`
	AdditionalProperties *Schema               `json:"additionalProperties,omitempty"`

	// Array items
	Items    *SchemaRef `json:"items,omitempty"`
	MinItems *int       `json:"minItems,omitempty"`
	MaxItems *int       `json:"maxItems,omitempty"`

	// String constraints
	MinLength *int   `json:"minLength,omitempty"`
	MaxLength *int   `json:"maxLength,omitempty"`
	Pattern   string `json:"pattern,omitempty"`

	// Number constraints
	Minimum *float64 `json:"minimum,omitempty"`
	Maximum *float64 `json:"maximum,omitempty"`
	Enum    []any    `json:"enum,omitempty"`

	// References
	Ref string `json:"$ref,omitempty"`

	// Composition
	AllOf []*SchemaRef `json:"allOf,omitempty"`
	OneOf []*SchemaRef `json:"oneOf,omitempty"`
	AnyOf []*SchemaRef `json:"anyOf,omitempty"`
	Not   *SchemaRef   `json:"not,omitempty"`
	// contains filtered or unexported fields
}

Schema represents a JSON Schema in OpenAPI

func (Schema) GetName

func (s Schema) GetName() string

type SchemaRef

type SchemaRef struct {
	Ref   string
	Value *Schema
}

SchemaRef represents a reference to a schema

type SecurityRequirement

type SecurityRequirement map[string][]string

SecurityRequirement represents a security requirement Key is the security scheme name, value is list of scopes

type SecurityScheme

type SecurityScheme struct {
	Type             string      `json:"type"` // http, apiKey, oauth2, openIdConnect
	Description      string      `json:"description,omitempty"`
	Name             string      `json:"name,omitempty"`   // For apiKey type
	In               string      `json:"in,omitempty"`     // For apiKey type: header, query, cookie
	Scheme           string      `json:"scheme,omitempty"` // For http type: bearer, basic, etc.
	BearerFormat     string      `json:"bearerFormat,omitempty"`
	Flows            *OAuthFlows `json:"flows,omitempty"`
	OpenIDConnectURL string      `json:"openIdConnectUrl,omitempty"`
}

SecurityScheme represents a security scheme definition

func (*SecurityScheme) Validate

func (s *SecurityScheme) Validate() error

Validate checks if a security scheme is valid

type SecuritySchemes

type SecuritySchemes map[string]*SecurityScheme

SecuritySchemes is a map of security scheme definitions

type Server

type Server struct {
	URL         string
	Description string
	Variables   map[string]*ServerVariable
}

Server represents a server URL

type ServerVariable

type ServerVariable struct {
	Enum        []string
	Default     string
	Description string
}

ServerVariable represents a server variable

type Specification

type Specification struct {
	OpenAPI    string
	Info       *Info
	Paths      map[string]*PathItem
	Components *Components
	Servers    []*Server
}

Specification represents a complete OpenAPI specification

func BuildCoreSpecification

func BuildCoreSpecification(info *Info, servers ...*Server) (*Specification, error)

BuildCoreSpecification converts registered Gin endpoints to Specification

func NewSpecification

func NewSpecification(openAPIVersion string, info *Info) *Specification

NewSpecification creates a new specification

func (*Specification) AddPath

func (s *Specification) AddPath(path string, pathItem *PathItem)

AddPath adds or updates a path item

func (*Specification) AddSecurityScheme

func (s *Specification) AddSecurityScheme(name string, scheme *SecurityScheme) error

AddSecurityScheme adds a security scheme to components

func (*Specification) AddServer

func (s *Specification) AddServer(server *Server)

AddServer adds a server to the specification

func (*Specification) Validate

func (s *Specification) Validate() error

Validate validates the specification

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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