Documentation
¶
Index ¶
- func APIKeyMiddleware(validator AuthorizationService, scheme SecurityScheme) fiber.Handler
- func AWSSignatureMiddleware(validator AuthorizationService) fiber.Handler
- func BasicAuthMiddleware(validator AuthorizationService) fiber.Handler
- func BearerTokenMiddleware(validator AuthorizationService) fiber.Handler
- func ConditionalAuthMiddleware(authMiddleware fiber.Handler, excludePaths ...string) fiber.Handler
- func DefaultNotFoundHandler() fiber.Handler
- func Delete[TInput any, TOutput any, TError any](router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], ...)
- func Get[TInput any, TOutput any, TError any](router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], ...)
- func Head[TInput any, TOutput any, TError any](router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], ...)
- func Method[TInput any, TOutput any, TError any](router OApiRouter, m string, path string, ...)
- func MultiSchemeAuthMiddleware(authService AuthorizationService, config Config) fiber.Handler
- func Patch[TInput any, TOutput any, TError any](router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], ...)
- func Post[TInput any, TOutput any, TError any](router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], ...)
- func Put[TInput any, TOutput any, TError any](router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], ...)
- func RequireResourceAccess(c fiber.Ctx, authService AuthorizationService, ...) error
- func RoleGuard(validator AuthorizationService, requiredRoles ...string) fiber.Handler
- func SmartAuthMiddleware(authService AuthorizationService, config Config) fiber.Handler
- type APIKeyValidator
- type AWSSignatureParams
- type AWSSignatureValidator
- type AuthContext
- type AuthError
- type AuthErrorHandler
- type AuthorizationService
- type BasicAuthValidator
- type Config
- type DocConfig
- type ErrorEnvelope
- type ErrorResponse
- type HTTPDescriptionError
- type HTTPStatusError
- type HandlerFunc
- type OApiApp
- func (o *OApiApp) Config() Config
- func (o *OApiApp) GenerateOpenAPISpec() map[string]interface{}
- func (o *OApiApp) GenerateOpenAPISpecYAML() (string, error)
- func (o *OApiApp) GetApp() *OApiApp
- func (o *OApiApp) GetOperations() []OpenAPIOperation
- func (o *OApiApp) GetPrefix() string
- func (app *OApiApp) Group(prefix string, handlers ...fiber.Handler) *OApiGroup
- func (o *OApiApp) Listen(addr string) error
- func (o *OApiApp) SetupDocs(config ...DocConfig)
- func (o *OApiApp) Use(middleware fiber.Handler)
- func (o *OApiApp) UseNotFoundHandler()
- type OApiGroup
- type OApiRouter
- type OpenAPIOperation
- type OpenAPIOptions
- func WithAllRoles(options OpenAPIOptions, roles ...string) OpenAPIOptions
- func WithPermissions(options OpenAPIOptions, permissions ...string) OpenAPIOptions
- func WithResourceType(options OpenAPIOptions, resourceType string) OpenAPIOptions
- func WithRoles(options OpenAPIOptions, roles ...string) OpenAPIOptions
- func WithSecurity(options OpenAPIOptions, security interface{}) OpenAPIOptions
- func WithSecurityDisabled(options OpenAPIOptions) OpenAPIOptions
- type OpenAPIParameter
- type OpenAPIRequestBody
- type OpenAPIResponse
- type PathInfo
- type ResourcePermission
- type ResponseContext
- type ScopeError
- type SecurityScheme
- type ValidationErrorEntry
- type ValidationErrorHandler
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func APIKeyMiddleware ¶
func APIKeyMiddleware(validator AuthorizationService, scheme SecurityScheme) fiber.Handler
APIKeyMiddleware creates a standalone middleware for API Key authentication. The authService must implement the APIKeyValidator interface.
func AWSSignatureMiddleware ¶
func AWSSignatureMiddleware(validator AuthorizationService) fiber.Handler
AWSSignatureMiddleware creates a standalone middleware for AWS Signature V4 authentication. The authService must implement the AWSSignatureValidator interface.
func BasicAuthMiddleware ¶
func BasicAuthMiddleware(validator AuthorizationService) fiber.Handler
BasicAuthMiddleware creates a standalone middleware for HTTP Basic authentication. The authService must implement the BasicAuthValidator interface.
func BearerTokenMiddleware ¶
func BearerTokenMiddleware(validator AuthorizationService) fiber.Handler
BearerTokenMiddleware creates a JWT/Bearer middleware
func ConditionalAuthMiddleware ¶
ConditionalAuthMiddleware creates middleware that applies only to specified routes
func DefaultNotFoundHandler ¶
DefaultNotFoundHandler returns the default envelope-producing fiber.Handler without any operation-aware 405 detection. Useful for users who manage their own fiber.Config and want to install the catch-all outside of fiber-oapi.
func Delete ¶
func Delete[TInput any, TOutput any, TError any]( router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], options OpenAPIOptions, )
Delete defines a DELETE operation for the OpenAPI documentation
func Get ¶
func Get[TInput any, TOutput any, TError any]( router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], options OpenAPIOptions, )
Get defines a GET operation for the OpenAPI documentation
func Head ¶
func Head[TInput any, TOutput any, TError any]( router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], options OpenAPIOptions, )
Head defines a HEAD operation for the OpenAPI documentation
func Method ¶
func Method[TInput any, TOutput any, TError any]( router OApiRouter, m string, path string, handler HandlerFunc[TInput, TOutput, TError], options OpenAPIOptions, )
Method defines a generic method for registering HTTP operations with OpenAPI documentation
func MultiSchemeAuthMiddleware ¶
func MultiSchemeAuthMiddleware(authService AuthorizationService, config Config) fiber.Handler
MultiSchemeAuthMiddleware creates middleware that tries configured security schemes. It iterates over DefaultSecurity requirements (OR semantics) and validates using the appropriate scheme handler.
func Patch ¶
func Patch[TInput any, TOutput any, TError any]( router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], options OpenAPIOptions, )
Patch defines a PATCH operation for the OpenAPI documentation
func Post ¶
func Post[TInput any, TOutput any, TError any]( router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], options OpenAPIOptions, )
Post defines a POST operation for the OpenAPI documentation
func Put ¶
func Put[TInput any, TOutput any, TError any]( router OApiRouter, path string, handler HandlerFunc[TInput, TOutput, TError], options OpenAPIOptions, )
Put defines a PUT operation for the OpenAPI documentation
func RequireResourceAccess ¶
func RequireResourceAccess(c fiber.Ctx, authService AuthorizationService, resourceType, resourceID, action string) error
RequireResourceAccess checks permissions in handlers
func RoleGuard ¶
func RoleGuard(validator AuthorizationService, requiredRoles ...string) fiber.Handler
RoleGuard middleware for role verification
func SmartAuthMiddleware ¶
func SmartAuthMiddleware(authService AuthorizationService, config Config) fiber.Handler
SmartAuthMiddleware creates middleware that automatically excludes documentation routes. When SecuritySchemes are configured, it uses MultiSchemeAuthMiddleware for dispatch. Otherwise, it falls back to BearerTokenMiddleware for backward compatibility.
Types ¶
type APIKeyValidator ¶
type APIKeyValidator interface {
ValidateAPIKey(key string, location string, paramName string) (*AuthContext, error)
}
APIKeyValidator is an optional interface for services that support API Key authentication (in header, query, or cookie).
type AWSSignatureParams ¶
type AWSSignatureParams struct {
// Parsed from "Credential=AKID/date/region/service/aws4_request"
AccessKeyID string
Date string
Region string
Service string
// Parsed from "SignedHeaders=host;x-amz-date;..."
SignedHeaders []string
// The raw signature hex string
Signature string
// The raw Authorization header for custom verification
RawHeader string
// Request metadata needed for signature verification
Method string
Path string
QueryString string
Headers map[string]string
Body []byte
}
AWSSignatureParams contains the parsed components of an AWS SigV4 Authorization header.
type AWSSignatureValidator ¶
type AWSSignatureValidator interface {
ValidateAWSSignature(params *AWSSignatureParams) (*AuthContext, error)
}
AWSSignatureValidator is an optional interface for services that support AWS Signature V4 authentication. The library parses the Authorization header and passes structured data; the implementation handles the actual cryptographic verification.
type AuthContext ¶
type AuthContext struct {
UserID string `json:"user_id"`
Roles []string `json:"roles"`
Scopes []string `json:"scopes"`
Claims map[string]interface{} `json:"claims"`
}
AuthContext contains user authentication details
func GetAuthContext ¶
func GetAuthContext(c fiber.Ctx) (*AuthContext, error)
GetAuthContext extracts the authentication context from Fiber
type AuthError ¶
AuthError represents an authentication or authorization failure with an HTTP status code.
type AuthErrorHandler ¶
AuthErrorHandler is a function type for handling authentication/authorization errors It receives the fiber context and the AuthError, and returns a fiber error response
type AuthorizationService ¶
type AuthorizationService interface {
// Authentication
ValidateToken(token string) (*AuthContext, error)
// Global authorization (roles/scopes)
HasRole(ctx *AuthContext, role string) bool
HasScope(ctx *AuthContext, scope string) bool
// Dynamic authorization on resources
CanAccessResource(ctx *AuthContext, resourceType, resourceID, action string) (bool, error)
GetUserPermissions(ctx *AuthContext, resourceType, resourceID string) (*ResourcePermission, error)
}
AuthorizationService interface for permission checks
type BasicAuthValidator ¶
type BasicAuthValidator interface {
ValidateBasicAuth(username, password string) (*AuthContext, error)
}
BasicAuthValidator is an optional interface for services that support HTTP Basic authentication. Implement this alongside AuthorizationService to enable Basic Auth validation.
type Config ¶
type Config struct {
EnableValidation bool // Enable request validation (default: true)
EnableOpenAPIDocs bool // Enable automatic docs setup (default: true)
EnableAuthorization bool // Enable authorization validation (default: false)
OpenAPIDocsPath string // Path for documentation UI (default: "/docs")
OpenAPIJSONPath string // Path for OpenAPI JSON spec (default: "/openapi.json")
OpenAPIYamlPath string // Path for OpenAPI YAML spec (default: "/openapi.yaml")
OpenAPITitle string // Title of the OpenAPI spec (default: "Fiber OpenAPI")
OpenAPIDescription string // Description of the OpenAPI spec (default: "API documentation generated by fiber-oapi")
OpenAPIVersion string // Version of the OpenAPI spec (default: "1.0.0")
AuthService AuthorizationService // Service for handling authentication and authorization
SecuritySchemes map[string]SecurityScheme // OpenAPI security schemes
DefaultSecurity []map[string][]string // Default security requirements
ValidationErrorHandler ValidationErrorHandler // Custom handler for validation errors
AuthErrorHandler AuthErrorHandler // Custom handler for auth errors (401/403/5xx)
NotFoundHandler fiber.Handler // Custom handler for unmatched routes. Receives a raw fiber.Ctx and owns the response (status + body). To reuse the library's envelope shape, call NotFoundEnvelope(c). Has no effect unless UseNotFoundHandler() is also called.
// DefaultErrorShape, when non-nil, replaces the built-in ErrorEnvelope
// across the library — both at runtime (parse, auth, 404/405 responses)
// and in the generated OpenAPI spec. Pass an empty/zero instance of any
// struct (or pointer-to-struct); the library fills its Code/StatusCode,
// Message/Description/Msg, Type, and Details fields per error category via
// reflection.
//
// Note: 422 validation responses intentionally keep the rich ErrorEnvelope
// shape (one entry per failing field) even when DefaultErrorShape is set.
// Leaving DefaultErrorShape nil keeps the default ErrorEnvelope everywhere.
DefaultErrorShape any
IncludeInvalidValueInErrors bool // Include offending value in default error envelope (default: false — may leak secrets)
}
Config represents configuration for the OApi wrapper
type DocConfig ¶
type DocConfig struct {
Title string
Description string
Version string
DocsPath string // Path where docs will be served, default: "/docs"
JSONPath string // Path where OpenAPI JSON will be served, default: "/openapi.json"
YamlPath string // Path where OpenAPI YAML will be served, default: "/openapi.yaml"
}
DocConfig contains configuration for the documentation
func DefaultDocConfig ¶
func DefaultDocConfig() DocConfig
DefaultDocConfig returns default documentation configuration
type ErrorEnvelope ¶
type ErrorEnvelope struct {
Errors []ValidationErrorEntry `json:"errors"`
ResponseContext ResponseContext `json:"response_context"`
}
ErrorEnvelope is the default response shape for validation, parsing and auth errors. It carries one entry per failing field plus a context block that lets callers correlate the response with their tracing setup.
func NotFoundEnvelope ¶
func NotFoundEnvelope(c fiber.Ctx) ErrorEnvelope
NotFoundEnvelope is the public counterpart to the internal builder: it produces the default 404 ErrorEnvelope for a request. Custom NotFoundHandler implementations can call it to reuse the library's shape while overriding only the response status or body.
type ErrorResponse ¶
type ErrorResponse struct {
Code int `json:"code"`
Details string `json:"details"`
Type string `json:"type"`
}
ErrorResponse is the legacy flat error shape. Still emitted by handleCustomError when a handler returns a non-zero TError, so existing custom error types keep working. New code should prefer ErrorEnvelope, which is what the default validation / parse / auth handlers now produce.
type HTTPDescriptionError ¶
type HTTPDescriptionError interface {
Description() string
}
HTTPDescriptionError is an optional interface that lets a custom error instance provide the OpenAPI description string explicitly, bypassing the field-name fallback (Message → Description → Msg → HTTP reason phrase).
type HTTPStatusError ¶
type HTTPStatusError interface {
HTTPStatus() int
}
HTTPStatusError is an optional interface a custom error instance can implement to expose its status code directly, bypassing field reflection.
type HandlerFunc ¶
type HandlerFunc[TInput any, TOutput any, TError any] func(c fiber.Ctx, input TInput) (TOutput, TError)
HandlerFunc represents a handler function with typed input and output
type OApiApp ¶
type OApiApp struct {
// contains filtered or unexported fields
}
OApiApp wraps fiber.App with OpenAPI capabilities
func (*OApiApp) GenerateOpenAPISpec ¶
GenerateOpenAPISpec generates a complete OpenAPI 3.0 specification
func (*OApiApp) GenerateOpenAPISpecYAML ¶
GenerateOpenAPISpecYAML generates the OpenAPI spec in YAML format
func (*OApiApp) GetOperations ¶
func (o *OApiApp) GetOperations() []OpenAPIOperation
GetOperations returns all registered operations (useful for testing and documentation generation)
func (*OApiApp) UseNotFoundHandler ¶
func (o *OApiApp) UseNotFoundHandler()
UseNotFoundHandler installs a catch-all middleware that responds with the fiber-oapi ErrorEnvelope when no other route matches the request.
Call this AFTER registering every route. The catch-all is installed via fiber.App.Use, which Fiber matches in registration order — install it before any route and that route will be unreachable. Calling the method more than once on the same OApiApp is a no-op after the first install.
The default handler does three things beyond emitting the 404 envelope:
- HEAD requests get a bodyless 404 (HTTP-conformant).
- OPTIONS requests fall through to the next handler so downstream CORS middleware can answer preflights.
- When the requested path is registered under another HTTP method, the response is 405 with an Allow header listing the supported methods.
To customise the response, set Config.NotFoundHandler. The handler runs in place of the default and receives a raw fiber.Ctx — it owns the entire response (status code and body). Call NotFoundEnvelope(c) to reuse the library's envelope shape from inside a custom handler.
type OApiGroup ¶
type OApiGroup struct {
fiber.Router // Embedded fiber.Router (includes all standard Fiber methods)
// contains filtered or unexported fields
}
OApiGroup wraps a fiber.Router and adds OpenAPI methods
func Group ¶
func Group(router OApiRouter, prefix string, handlers ...fiber.Handler) *OApiGroup
Group creates a new group from an OApiRouter (app or group)
type OApiRouter ¶
OApiRouter interface that both OApiApp and OApiGroup implement
type OpenAPIOperation ¶
type OpenAPIOperation struct {
Method string
Path string
Options OpenAPIOptions
InputType reflect.Type
OutputType reflect.Type
ErrorType reflect.Type
}
OpenAPIOperation represents a registered operation
type OpenAPIOptions ¶
type OpenAPIOptions struct {
OperationID string `json:"operationId,omitempty"`
Tags []string `json:"tags,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Parameters []map[string]any `json:"parameters,omitempty"`
Security any `json:"security,omitempty"` // Can be []map[string][]string or "disabled"
RequiredRoles []string `json:"-"` // Roles required to access this route (OR semantics by default)
RequireAllRoles bool `json:"-"` // If true, all RequiredRoles must match (AND semantics)
RequiredPermissions []string `json:"-"` // Ex: ["document:read", "workspace:admin"]
ResourceType string `json:"-"` // Type de ressource concernée
// Hidden, when true, excludes this operation from the generated OpenAPI
// spec. The route is still registered on the underlying fiber.App and
// serves traffic normally — it just does not appear under paths in the
// generated JSON/YAML and any type only used by hidden operations does
// not leak into components.schemas. Useful for internal admin endpoints,
// in-progress routes, or anything you want to ship without publishing.
Hidden bool `json:"-"`
// Errors declares the custom error responses this operation can emit. Each
// entry is an instance of any struct (or pointer-to-struct) describing one
// error case. The library inspects each entry to populate the generated
// OpenAPI spec:
// - status code: from a HTTPStatus() int method, or from a "StatusCode"
// or "Code" int field (defaults to 500 if none found)
// - description: from a Description() string method, or from "Message",
// "Description", or "Msg" string fields (falls back to the HTTP reason
// phrase for the status code)
// - schema: generated from the entry's reflect.Type and shared via $ref
// when the type is named, so multiple entries with the same shape do
// not duplicate the schema
// - example: the entry value itself, marshalled as JSON
//
// At runtime the handler returns one of these instances via its TError
// generic parameter (which can be `error`, a concrete `*ErrorResponse`,
// or any other type) and the library emits it with the matching status.
Errors []any `json:"-"`
}
OpenAPIOptions represents options for OpenAPI operations
func WithAllRoles ¶
func WithAllRoles(options OpenAPIOptions, roles ...string) OpenAPIOptions
WithAllRoles adds required roles to a route with AND semantics (user needs all of them)
func WithPermissions ¶
func WithPermissions(options OpenAPIOptions, permissions ...string) OpenAPIOptions
WithPermissions adds required permissions for documentation
func WithResourceType ¶
func WithResourceType(options OpenAPIOptions, resourceType string) OpenAPIOptions
WithResourceType defines the concerned resource type
func WithRoles ¶
func WithRoles(options OpenAPIOptions, roles ...string) OpenAPIOptions
WithRoles adds required roles to a route with OR semantics (user needs at least one)
func WithSecurity ¶
func WithSecurity(options OpenAPIOptions, security interface{}) OpenAPIOptions
WithSecurity adds security to a route
func WithSecurityDisabled ¶
func WithSecurityDisabled(options OpenAPIOptions) OpenAPIOptions
WithSecurityDisabled disables security for a route
type OpenAPIParameter ¶
type OpenAPIRequestBody ¶
type OpenAPIResponse ¶
type ResourcePermission ¶
type ResourcePermission struct {
ResourceType string `json:"resource_type"`
ResourceID string `json:"resource_id"`
Actions []string `json:"actions"` // ["read", "write", "delete", "share"]
}
ResourcePermission defines permissions on a resource
type ResponseContext ¶
type ResponseContext struct {
ResponseID string `json:"response_id,omitempty"`
}
ResponseContext carries metadata that helps a client correlate the response with their tracing setup. ResponseID mirrors the incoming X-Request-Id header when present, otherwise it is left empty.
type ScopeError ¶
type ScopeError struct {
Scope string
}
ScopeError represents an authorization failure due to missing scopes (403, not 401).
func (*ScopeError) Error ¶
func (e *ScopeError) Error() string
type SecurityScheme ¶
type SecurityScheme struct {
Type string `json:"type" yaml:"type"`
Scheme string `json:"scheme,omitempty" yaml:"scheme,omitempty"`
BearerFormat string `json:"bearerFormat,omitempty" yaml:"bearerFormat,omitempty"`
In string `json:"in,omitempty" yaml:"in,omitempty"`
Name string `json:"name,omitempty" yaml:"name,omitempty"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
Flows map[string]interface{} `json:"flows,omitempty" yaml:"flows,omitempty"`
}
SecurityScheme for OpenAPI
type ValidationErrorEntry ¶
type ValidationErrorEntry struct {
Type string `json:"type"` // validation_error | type_error | parse_error | authentication_error | authorization_error | not_found | method_not_allowed
Code int `json:"code"` // HTTP status code carried in the response
Loc []any `json:"loc"` // path to the field, e.g. ["body", "address", "zipcode"]
Field string `json:"field,omitempty"` // leaf field name, redundant with Loc but convenient
Msg string `json:"msg"` // human-readable message
Constraint string `json:"constraint,omitempty"` // failing rule, e.g. "min=11", "required", "email"
Value any `json:"value,omitempty"` // offending value (opt-in via Config.IncludeInvalidValueInErrors)
}
ValidationErrorEntry describes a single failure (one field, one constraint). The same shape is used for body validation errors, JSON type mismatches and authentication / authorization failures so clients only have to parse one envelope.