fiberoapi

package module
v1.9.3 Latest Latest
Warning

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

Go to latest
Published: May 4, 2026 License: MIT Imports: 13 Imported by: 0

README

Fiber OpenAPI

A Go library that extends Fiber to add automatic OpenAPI documentation generation with built-in validation, authentication, and role-based access control.

Features

  • Complete HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD) with automatic validation
  • Group support with OpenAPI methods available on both app and groups
  • Unified API with interface-based approach for seamless app/group usage
  • Powerful validation via github.com/go-playground/validator/v10
  • Multiple authentication schemes: Bearer, Basic Auth, API Key, AWS SigV4
  • Declarative role-based access control with OR/AND semantics
  • Custom error handlers for validation and authentication errors
  • Per-route security overrides and public routes
  • Type safety with Go generics
  • OpenAPI 3.0 documentation in JSON and YAML formats
  • Redoc documentation UI for modern, responsive API documentation
  • OpenAPI extensions (x-required-roles, x-required-roles-mode)
  • Conditional auth middleware for flexible authentication strategies

Installation

go get github.com/labbs/fiber-oapi

Quick Start

package main

import (
    "github.com/gofiber/fiber/v2"
    fiberoapi "github.com/labbs/fiber-oapi"
)

func main() {
    app := fiber.New()
    oapi := fiberoapi.New(app)

    fiberoapi.Get(oapi, "/hello/:name",
        func(c *fiber.Ctx, input struct {
            Name string `path:"name" validate:"required,min=2"`
        }) (fiber.Map, *fiberoapi.ErrorResponse) {
            return fiber.Map{"message": "Hello " + input.Name}, nil
        },
        fiberoapi.OpenAPIOptions{
            Summary: "Say hello",
            Tags:    []string{"greeting"},
        })

    // Docs at /docs, spec at /openapi.json and /openapi.yaml
    app.Listen(":3000")
}

Configuration

type Config struct {
    EnableValidation       bool                      // Enable input validation (default: true)
    EnableOpenAPIDocs      bool                      // Enable automatic docs setup (default: true)
    EnableAuthorization    bool                      // Enable auth validation (default: false)
    OpenAPIDocsPath        string                    // Path for docs UI (default: "/docs")
    OpenAPIJSONPath        string                    // Path for JSON spec (default: "/openapi.json")
    OpenAPIYamlPath        string                    // Path for YAML spec (default: "/openapi.yaml")
    AuthService            AuthorizationService      // Service for handling auth
    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)
}

Default config when none is provided:

  • Validation: enabled
  • Documentation: enabled
  • Authorization: disabled
  • Docs path: /docs
  • JSON spec path: /openapi.json
  • YAML spec path: /openapi.yaml

HTTP Methods

All methods work with both the main app and groups:

fiberoapi.Get(router, path, handler, options)
fiberoapi.Post(router, path, handler, options)
fiberoapi.Put(router, path, handler, options)
fiberoapi.Patch(router, path, handler, options)
fiberoapi.Delete(router, path, handler, options)
fiberoapi.Head(router, path, handler, options)
fiberoapi.Method(method, router, path, handler, options) // Custom HTTP method

Parameter Types

type MyInput struct {
    ID     string `path:"id" validate:"required"`           // Path parameter
    Filter string `query:"filter" validate:"omitempty"`      // Query parameter
    Auth   string `header:"Authorization"`                   // Header parameter
    Title  string `json:"title" validate:"required,min=1"`   // JSON body field
}

Special tags:

  • openapi:"-" — Exclude a field from the OpenAPI schema (the field still works in the handler)
  • description:"text" — Add a description to the field in the spec
  • resource:"document" — Mark field as a resource identifier for dynamic authorization
  • action:"write" — Specify the action for resource access checks

Groups

app := fiber.New()
oapi := fiberoapi.New(app)

v1 := fiberoapi.Group(oapi, "/api/v1")
users := fiberoapi.Group(v1, "/users")

// OpenAPI methods on groups
fiberoapi.Get(users, "/:id", getUser, options)   // Registers as GET /api/v1/users/{id}
fiberoapi.Post(users, "/", createUser, options)

// Standard Fiber middleware still works
v1.Use(authMiddleware)

Validation

Uses validator/v10. Common tags:

type Input struct {
    Name   string `json:"name" validate:"required,min=3,max=50"`
    Email  string `json:"email" validate:"required,email"`
    Age    int    `json:"age" validate:"min=13,max=120"`
    Role   string `json:"role" validate:"oneof=admin user guest"`
    Tags   []string `json:"tags" validate:"dive,min=1"`
}

Authentication & Authorization

Supported Security Schemes
Scheme Config Validator Interface
Bearer Token Type: "http", Scheme: "bearer" AuthorizationService (built-in)
HTTP Basic Type: "http", Scheme: "basic" BasicAuthValidator
API Key Type: "apiKey", In: "header"/"query"/"cookie" APIKeyValidator
AWS SigV4 Type: "http", Scheme: "AWS4-HMAC-SHA256" AWSSignatureValidator
Setup

Implement AuthorizationService (required) and any additional validator interfaces:

type MyAuthService struct{}

// Required: AuthorizationService
func (s *MyAuthService) ValidateToken(token string) (*fiberoapi.AuthContext, error) { ... }
func (s *MyAuthService) HasRole(ctx *fiberoapi.AuthContext, role string) bool { ... }
func (s *MyAuthService) HasScope(ctx *fiberoapi.AuthContext, scope string) bool { ... }
func (s *MyAuthService) CanAccessResource(ctx *fiberoapi.AuthContext, resourceType, resourceID, action string) (bool, error) { ... }
func (s *MyAuthService) GetUserPermissions(ctx *fiberoapi.AuthContext, resourceType, resourceID string) (*fiberoapi.ResourcePermission, error) { ... }

// Optional: BasicAuthValidator
func (s *MyAuthService) ValidateBasicAuth(username, password string) (*fiberoapi.AuthContext, error) { ... }

// Optional: APIKeyValidator
func (s *MyAuthService) ValidateAPIKey(key, location, paramName string) (*fiberoapi.AuthContext, error) { ... }

// Optional: AWSSignatureValidator
func (s *MyAuthService) ValidateAWSSignature(params *fiberoapi.AWSSignatureParams) (*fiberoapi.AuthContext, error) { ... }

Configure multiple security schemes (OR semantics between them):

config := fiberoapi.Config{
    EnableAuthorization: true,
    AuthService:         &MyAuthService{},
    SecuritySchemes: map[string]fiberoapi.SecurityScheme{
        "bearerAuth": {
            Type:         "http",
            Scheme:       "bearer",
            BearerFormat: "JWT",
            Description:  "JWT Bearer token",
        },
        "basicAuth": {
            Type:        "http",
            Scheme:      "basic",
            Description: "HTTP Basic authentication",
        },
        "apiKeyAuth": {
            Type:        "apiKey",
            In:          "header",
            Name:        "X-API-Key",
            Description: "API Key via header",
        },
    },
    // Any of these schemes can authenticate a request (OR semantics)
    DefaultSecurity: []map[string][]string{
        {"bearerAuth": {}},
        {"basicAuth": {}},
        {"apiKeyAuth": {}},
    },
}
oapi := fiberoapi.New(app, config)
Public vs Protected Routes
// Public route — no authentication
fiberoapi.Get(oapi, "/health", handler,
    fiberoapi.OpenAPIOptions{
        Summary:  "Health check",
        Security: "disabled",
    })

// Protected route — uses default security
fiberoapi.Get(oapi, "/profile", handler,
    fiberoapi.OpenAPIOptions{
        Summary: "Get profile",
    })

// Per-route security override
fiberoapi.Get(oapi, "/admin", handler,
    fiberoapi.WithSecurity(
        fiberoapi.OpenAPIOptions{Summary: "Admin endpoint"},
        []map[string][]string{{"bearerAuth": {}}}, // Only bearer, not API key
    ))
Declarative Role-Based Access Control

Roles are checked automatically before your handler runs. No manual checks needed.

// OR semantics: user needs at least ONE of the listed roles
fiberoapi.Get(oapi, "/documents/:id", handler,
    fiberoapi.WithRoles(
        fiberoapi.OpenAPIOptions{Summary: "Get document", Tags: []string{"documents"}},
        "admin", "editor",  // admin OR editor can access
    ))

// AND semantics: user needs ALL of the listed roles
fiberoapi.Delete(oapi, "/documents/:id", handler,
    fiberoapi.WithAllRoles(
        fiberoapi.OpenAPIOptions{Summary: "Delete document", Tags: []string{"documents"}},
        "admin", "moderator",  // must be admin AND moderator
    ))

// Inline via OpenAPIOptions
fiberoapi.Get(oapi, "/settings", handler,
    fiberoapi.OpenAPIOptions{
        Summary:         "Settings",
        RequiredRoles:   []string{"admin", "superadmin"},
        RequireAllRoles: false,  // OR semantics (default)
    })

Roles appear in the OpenAPI spec as extensions:

{
    "x-required-roles": ["admin", "editor"],
    "x-required-roles-mode": "any"
}
Permissions and Resource Access
// RequiredPermissions are documented in the OpenAPI spec description
fiberoapi.Put(oapi, "/documents/:id", handler,
    fiberoapi.OpenAPIOptions{
        Summary:             "Update document",
        RequiredRoles:       []string{"editor"},
        RequiredPermissions: []string{"document:write"},
    })

// Resource-based access via struct tags
type UpdateDocInput struct {
    DocumentID string `path:"documentId" validate:"required" resource:"document" action:"write"`
    Title      string `json:"title" validate:"required"`
}

// Dynamic resource access check in handler
fiberoapi.RequireResourceAccess(c, authService, "document", docID, "delete")
Authentication Context

Access the authenticated user in handlers:

fiberoapi.Get(oapi, "/me", func(c *fiber.Ctx, input struct{}) (fiber.Map, *fiberoapi.ErrorResponse) {
    authCtx, err := fiberoapi.GetAuthContext(c)
    if err != nil {
        return nil, &fiberoapi.ErrorResponse{Code: 401, Details: "Not authenticated"}
    }
    return fiber.Map{
        "user_id": authCtx.UserID,
        "roles":   authCtx.Roles,
        "scopes":  authCtx.Scopes,
        "claims":  authCtx.Claims,
    }, nil
}, fiberoapi.OpenAPIOptions{Summary: "Current user"})

Custom Error Handlers

Validation Errors
oapi := fiberoapi.New(app, fiberoapi.Config{
    ValidationErrorHandler: func(c *fiber.Ctx, err error) error {
        return c.Status(400).JSON(fiber.Map{
            "success": false,
            "error":   err.Error(),
        })
    },
})
Authentication/Authorization Errors
oapi := fiberoapi.New(app, fiberoapi.Config{
    EnableAuthorization: true,
    AuthService:         authService,
    AuthErrorHandler: func(c *fiber.Ctx, err *fiberoapi.AuthError) error {
        // err.StatusCode: 401, 403, or 5xx
        // err.Message: human-readable error message
        return c.Status(err.StatusCode).JSON(fiber.Map{
            "error":   err.Message,
            "status":  err.StatusCode,
        })
    },
})

Without custom handlers, default error responses are returned:

// 401 - Authentication failure
{"code": 401, "details": "invalid token", "type": "authentication_error"}

// 403 - Authorization failure
{"code": 403, "details": "requires one of: admin, editor", "type": "authorization_error"}

// 400 - Validation failure
{"code": 400, "details": "...", "type": "validation_error"}

Conditional Auth Middleware

Standalone middleware functions for use outside the declarative route system:

// Smart middleware that auto-detects security schemes and excludes doc routes
app.Use(fiberoapi.SmartAuthMiddleware(authService, config))

// Skip auth for specific paths
app.Use(fiberoapi.ConditionalAuthMiddleware(
    fiberoapi.BearerTokenMiddleware(authService),
    "/health", "/docs", "/openapi.json",
))

// Individual scheme middleware
app.Use(fiberoapi.BearerTokenMiddleware(authService))
app.Use(fiberoapi.BasicAuthMiddleware(authService))
app.Use(fiberoapi.APIKeyMiddleware(authService, scheme))
app.Use(fiberoapi.AWSSignatureMiddleware(authService))

// Role guard middleware
app.Use(fiberoapi.RoleGuard(authService, "admin"))

Security Helpers

opts := fiberoapi.OpenAPIOptions{Summary: "My endpoint"}

// Security
opts = fiberoapi.WithSecurity(opts, []map[string][]string{{"bearerAuth": {}}})
opts = fiberoapi.WithSecurityDisabled(opts)

// Roles
opts = fiberoapi.WithRoles(opts, "admin", "editor")       // OR semantics
opts = fiberoapi.WithAllRoles(opts, "admin", "moderator")  // AND semantics

// Documentation
opts = fiberoapi.WithPermissions(opts, "document:read", "document:write")
opts = fiberoapi.WithResourceType(opts, "document")

OpenAPI Spec Generation

The spec is available in both JSON and YAML:

// Automatic endpoints
// GET /openapi.json
// GET /openapi.yaml
// GET /docs (Redoc UI)

// Programmatic access
spec := oapi.GenerateOpenAPISpec()           // map[string]interface{}
yamlSpec, err := oapi.GenerateOpenAPISpecYAML() // string
Custom Documentation
oapi.SetupDocs(fiberoapi.DocConfig{
    Title:       "My API",
    Description: "My API description",
    Version:     "2.0.0",
    DocsPath:    "/documentation",
    JSONPath:    "/api-spec.json",
})

Testing

# Run all tests
go test -v ./...

# Run the auth example
go run _examples/auth/main.go
# Visit http://localhost:3002/docs

Testing with authentication:

# Bearer token
curl -H "Authorization: Bearer admin-token" http://localhost:3002/me

# Basic auth
curl --user admin:admin-pass http://localhost:3002/me

# API key
curl -H "X-API-Key: my-secret-api-key" http://localhost:3002/documents/doc-1

# Public endpoint
curl http://localhost:3002/health

Complete Example

See _examples/auth/main.go for a full working example with:

  • Multiple security schemes (Bearer, Basic, API Key, AWS SigV4)
  • Declarative role-based access control
  • Custom auth error handler
  • Public and protected routes
  • Resource-level authorization
  • OpenAPI documentation with security schemes

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIKeyMiddleware added in v1.8.0

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 added in v1.8.0

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 added in v1.8.0

func BasicAuthMiddleware(validator AuthorizationService) fiber.Handler

BasicAuthMiddleware creates a standalone middleware for HTTP Basic authentication. The authService must implement the BasicAuthValidator interface.

func BearerTokenMiddleware added in v1.4.0

func BearerTokenMiddleware(validator AuthorizationService) fiber.Handler

BearerTokenMiddleware creates a JWT/Bearer middleware

func ConditionalAuthMiddleware added in v1.4.0

func ConditionalAuthMiddleware(authMiddleware fiber.Handler, excludePaths ...string) fiber.Handler

ConditionalAuthMiddleware creates middleware that applies only to specified routes

func Delete added in v1.2.0

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 added in v1.2.0

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[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 added in v1.2.0

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 added in v1.8.0

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 added in v1.2.0

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 added in v1.2.0

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 added in v1.2.0

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 added in v1.4.0

func RequireResourceAccess(c *fiber.Ctx, authService AuthorizationService, resourceType, resourceID, action string) error

RequireResourceAccess checks permissions in handlers

func RoleGuard added in v1.4.0

func RoleGuard(validator AuthorizationService, requiredRoles ...string) fiber.Handler

RoleGuard middleware for role verification

func SmartAuthMiddleware added in v1.4.0

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 added in v1.8.0

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 added in v1.8.0

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 added in v1.8.0

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 added in v1.4.0

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 added in v1.4.0

func GetAuthContext(c *fiber.Ctx) (*AuthContext, error)

GetAuthContext extracts the authentication context from Fiber

type AuthError added in v1.8.0

type AuthError struct {
	StatusCode int
	Message    string
}

AuthError represents an authentication or authorization failure with an HTTP status code.

func (*AuthError) Error added in v1.8.0

func (e *AuthError) Error() string

type AuthErrorHandler added in v1.9.1

type AuthErrorHandler func(c *fiber.Ctx, err *AuthError) error

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 added in v1.4.0

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 added in v1.8.0

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")
	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)
}

Config represents configuration for the OApi wrapper

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration

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 ErrorResponse added in v1.3.0

type ErrorResponse struct {
	Code    int    `json:"code"`
	Details string `json:"details"`
	Type    string `json:"type"`
}

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 New

func New(app *fiber.App, config ...Config) *OApiApp

New creates a new OApiApp with optional configuration

func (*OApiApp) Config

func (o *OApiApp) Config() Config

Config returns the current configuration

func (*OApiApp) GenerateOpenAPISpec

func (o *OApiApp) GenerateOpenAPISpec() map[string]interface{}

GenerateOpenAPISpec generates a complete OpenAPI 3.0 specification

func (*OApiApp) GenerateOpenAPISpecYAML added in v1.5.0

func (o *OApiApp) GenerateOpenAPISpecYAML() (string, error)

GenerateOpenAPISpecYAML generates the OpenAPI spec in YAML format

func (*OApiApp) GetApp added in v1.2.0

func (o *OApiApp) GetApp() *OApiApp

Implement OApiRouter interface for OApiApp

func (*OApiApp) GetOperations

func (o *OApiApp) GetOperations() []OpenAPIOperation

GetOperations returns all registered operations (useful for testing and documentation generation)

func (*OApiApp) GetPrefix added in v1.2.0

func (o *OApiApp) GetPrefix() string

func (*OApiApp) Group added in v1.2.0

func (app *OApiApp) Group(prefix string, handlers ...fiber.Handler) *OApiGroup

Group creates a new OApiGroup that wraps a fiber.Router

func (*OApiApp) Listen added in v1.4.0

func (o *OApiApp) Listen(addr string) error

Listen starts the server on the given address

func (*OApiApp) SetupDocs

func (o *OApiApp) SetupDocs(config ...DocConfig)

SetupDocs configures documentation routes for the OApiApp

func (*OApiApp) Use added in v1.4.0

func (o *OApiApp) Use(middleware fiber.Handler)

Use adds middleware to the OApiApp

type OApiGroup added in v1.2.0

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 added in v1.2.0

func Group(router OApiRouter, prefix string, handlers ...fiber.Handler) *OApiGroup

Group creates a new group from an OApiRouter (app or group)

func (*OApiGroup) GetApp added in v1.2.0

func (g *OApiGroup) GetApp() *OApiApp

Implement OApiRouter interface for OApiGroup

func (*OApiGroup) GetPrefix added in v1.2.0

func (g *OApiGroup) GetPrefix() string

func (*OApiGroup) Group added in v1.2.0

func (g *OApiGroup) Group(prefix string, handlers ...fiber.Handler) *OApiGroup

Group creates a new sub-group within this group

func (*OApiGroup) Use added in v1.4.0

func (g *OApiGroup) Use(middleware fiber.Handler)

Use adds middleware to the OApiGroup

type OApiRouter added in v1.2.0

type OApiRouter interface {
	GetApp() *OApiApp
	GetPrefix() string
}

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
}

OpenAPIOptions represents options for OpenAPI operations

func WithAllRoles added in v1.9.2

func WithAllRoles(options OpenAPIOptions, roles ...string) OpenAPIOptions

WithAllRoles adds required roles to a route with AND semantics (user needs all of them)

func WithPermissions added in v1.4.0

func WithPermissions(options OpenAPIOptions, permissions ...string) OpenAPIOptions

WithPermissions adds required permissions for documentation

func WithResourceType added in v1.4.0

func WithResourceType(options OpenAPIOptions, resourceType string) OpenAPIOptions

WithResourceType defines the concerned resource type

func WithRoles added in v1.9.0

func WithRoles(options OpenAPIOptions, roles ...string) OpenAPIOptions

WithRoles adds required roles to a route with OR semantics (user needs at least one)

func WithSecurity added in v1.4.0

func WithSecurity(options OpenAPIOptions, security interface{}) OpenAPIOptions

WithSecurity adds security to a route

func WithSecurityDisabled added in v1.4.0

func WithSecurityDisabled(options OpenAPIOptions) OpenAPIOptions

WithSecurityDisabled disables security for a route

type OpenAPIParameter

type OpenAPIParameter struct {
	Name        string         `json:"name"`
	In          string         `json:"in"` // "path", "query", "header", "cookie"
	Required    bool           `json:"required,omitempty"`
	Description string         `json:"description,omitempty"`
	Schema      map[string]any `json:"schema"`
}

type OpenAPIRequestBody

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

type OpenAPIResponse

type OpenAPIResponse struct {
	Description string         `json:"description"`
	Content     map[string]any `json:"content,omitempty"`
}

type PathInfo

type PathInfo struct {
	Name   string
	IsPath bool
	Index  int // Position in the path for validation
}

PathInfo represents information about a path parameter

type ResourcePermission added in v1.4.0

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 ScopeError added in v1.8.0

type ScopeError struct {
	Scope string
}

ScopeError represents an authorization failure due to missing scopes (403, not 401).

func (*ScopeError) Error added in v1.8.0

func (e *ScopeError) Error() string

type SecurityScheme added in v1.4.0

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 ValidationErrorHandler added in v1.7.0

type ValidationErrorHandler func(c *fiber.Ctx, err error) error

ValidationErrorHandler is a function type for handling validation errors It receives the fiber context and the validation error, and returns a fiber error response

Jump to

Keyboard shortcuts

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