api

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AuthStrategyNone      = "none"
	AuthStrategyBearer    = "bearer"
	AuthStrategySignature = "signature"
)

Auth strategy constants.

View Source
const (
	VersionV1 = "v1"
	VersionV2 = "v2"
	VersionV3 = "v3"
	VersionV4 = "v4"
	VersionV5 = "v5"
	VersionV6 = "v6"
	VersionV7 = "v7"
	VersionV8 = "v8"
	VersionV9 = "v9"
)

Variables

View Source
var (
	// Resource errors.
	ErrEmptyResourceName       = errors.New("empty resource name")
	ErrInvalidResourceName     = errors.New("invalid resource name format")
	ErrResourceNameSlash       = errors.New("resource name cannot start or end with slash")
	ErrResourceNameDoubleSlash = errors.New("resource name cannot contain consecutive slashes")
	ErrInvalidResourceKind     = errors.New("invalid resource kind")

	// Version errors.
	ErrInvalidVersionFormat = errors.New("invalid version format, must match pattern v+digits (e.g., v1, v2, v10)")

	// Action errors.
	ErrEmptyActionName   = errors.New("empty action name")
	ErrInvalidActionName = errors.New("invalid action name format")

	// Decode errors.
	ErrInvalidParamsType = errors.New("invalid params type: must be pointer to struct")
	ErrInvalidMetaType   = errors.New("invalid meta type: must be pointer to struct")
)

Functions

func SubscribeAuditEvent added in v0.5.0

func SubscribeAuditEvent(subscriber event.Subscriber, handler func(context.Context, *AuditEvent)) event.UnsubscribeFunc

SubscribeAuditEvent subscribes to audit events. Returns an unsubscribe function that can be called to remove the subscription.

func ValidateActionName added in v0.6.0

func ValidateActionName(action string, kind Kind) error

ValidateActionName validates the action name based on the resource kind. For RPC, action must be snake_case (e.g., create, find_page). For REST, action format is "<method>" or "<method> <sub-resource>" (e.g., "get", "post user-friends").

Types

type AuditEvent added in v0.5.0

type AuditEvent struct {
	event.BaseEvent

	// Api identification
	Resource string `json:"resource"`
	Action   string `json:"action"`
	Version  string `json:"version"`

	// User identification
	UserID    string `json:"userId"`
	UserAgent string `json:"userAgent"`

	// Request information
	RequestID     string         `json:"requestId"`
	RequestIP     string         `json:"requestIp"`
	RequestParams map[string]any `json:"requestParams"`
	RequestMeta   map[string]any `json:"requestMeta"`

	// Response information
	ResultCode    int    `json:"resultCode"`
	ResultMessage string `json:"resultMessage"`
	ResultData    any    `json:"resultData"`

	// Performance metrics
	ElapsedTime int64 `json:"elapsedTime"` // Elapsed time in milliseconds
}

AuditEvent represents an Api request audit log event.

func NewAuditEvent added in v0.5.0

func NewAuditEvent(params AuditEventParams) *AuditEvent

NewAuditEvent creates a new audit event with the given parameters.

type AuditEventParams added in v0.18.0

type AuditEventParams struct {
	// Api identification
	Resource string
	Action   string
	Version  string

	// User identification
	UserID    string
	UserAgent string

	// Request information
	RequestID     string
	RequestIP     string
	RequestParams map[string]any
	RequestMeta   map[string]any

	// Response information
	ResultCode    int
	ResultMessage string
	ResultData    any

	// Performance metrics
	ElapsedTime int64
}

AuditEventParams contains parameters for creating an AuditEvent.

type AuthConfig added in v0.18.0

type AuthConfig struct {
	// Strategy specifies the auth strategy name. default is "bearer".
	// Built-in: "none", "bearer", "signature"
	// Custom strategies can be registered via AuthStrategyRegistry.
	Strategy string
	// Options holds strategy-specific configuration.
	Options map[string]any
}

AuthConfig defines authentication configuration for an operation.

func BearerAuth added in v0.18.0

func BearerAuth() *AuthConfig

BearerAuth creates an AuthConfig for BearerAuth token authentication.

func Public added in v0.18.0

func Public() *AuthConfig

Public creates an AuthConfig for public endpoints (no authentication).

func SignatureAuth added in v0.18.0

func SignatureAuth() *AuthConfig

SignatureAuth creates an AuthConfig for signature-based authentication.

func (*AuthConfig) Clone added in v0.18.0

func (c *AuthConfig) Clone() *AuthConfig

Clone creates a deep copy of the AuthConfig.

type AuthStrategy added in v0.18.0

type AuthStrategy interface {
	// Name returns the strategy name (used in AuthConfig.Strategy).
	Name() string
	// Authenticate validates credentials and returns principal.
	Authenticate(ctx fiber.Ctx, options map[string]any) (*security.Principal, error)
}

AuthStrategy handles authentication for a specific auth type.

type AuthStrategyRegistry added in v0.18.0

type AuthStrategyRegistry interface {
	// Register adds a strategy to the registry.
	Register(strategy AuthStrategy)
	// Get retrieves a strategy by name.
	Get(name string) (AuthStrategy, bool)
	// Names returns all registered strategy names.
	Names() []string
}

AuthStrategyRegistry manages authentication strategies.

type Engine added in v0.18.0

type Engine interface {
	// Register adds resources to the engine.
	Register(resources ...Resource) error
	// Lookup finds an operation by identifier.
	Lookup(id Identifier) *Operation
	// Mount attaches the engine to a Fiber router.
	Mount(router fiber.Router) error
}

Engine is the unified API engine that manages multiple routers.

type FactoryParamResolver added in v0.11.0

type FactoryParamResolver interface {
	// Type returns the parameter type this resolver handles.
	Type() reflect.Type
	// Resolve returns the parameter value (called once at startup).
	Resolve() (reflect.Value, error)
}

FactoryParamResolver resolves a factory function parameter at startup time. Factory functions enable dependency injection at startup while keeping handlers clean.

type HandlerAdapter added in v0.18.0

type HandlerAdapter interface {
	// Adapt converts the handler to a fiber.Handler.
	Adapt(handler any, op *Operation) (fiber.Handler, error)
}

HandlerAdapter converts various handler variants to fiber.Handler.

type HandlerParamResolver

type HandlerParamResolver interface {
	// Type returns the parameter type this resolver handles.
	Type() reflect.Type
	// Resolve extracts the parameter value from the request.
	Resolve(ctx fiber.Ctx) (reflect.Value, error)
}

HandlerParamResolver resolves a handler parameter from the request context.

type HandlerResolver added in v0.18.0

type HandlerResolver interface {
	// Resolve finds a handler on the resource and spec.
	// Returns the handler (any type) or an error if not found.
	Resolve(resource Resource, spec OperationSpec) (any, error)
}

HandlerResolver resolves a handler from a resource and spec.

type Identifier

type Identifier struct {
	Resource string `json:"resource" form:"resource" validate:"required,alphanum_us_slash" label_i18n:"api_request_resource"`
	Action   string `json:"action" form:"action" validate:"required" label_i18n:"api_request_action"`
	Version  string `json:"version" form:"version" validate:"required,alphanum" label_i18n:"api_request_version"`
}

Identifier uniquely identifies an API operation.

func (Identifier) String

func (id Identifier) String() string

String returns a string representation of the identifier.

type Kind added in v0.18.0

type Kind uint8
const (
	// KindRPC represents the KindRPC kind.
	KindRPC Kind = iota + 1
	// KindREST represents the KindREST kind.
	KindREST
)

func (Kind) String added in v0.18.0

func (k Kind) String() string

type M added in v0.7.0

type M struct{}

M is a sentinel type that marks a struct as API metadata. Embed this type in your metadata struct to enable automatic decoding from Request.Meta.

Example:

type PageMeta struct {
    api.M
    Page     int `json:"page"`
    Size     int `json:"size"`
}

type Meta

type Meta map[string]any

Meta holds API request metadata.

func (Meta) Decode added in v0.7.0

func (m Meta) Decode(out any) error

Decode decodes meta into a struct.

type Middleware added in v0.18.0

type Middleware interface {
	// Name returns the middleware identifier.
	Name() string
	// Order determines execution order.
	// Negative values execute before handler, positive after.
	// Lower values execute first within the same phase.
	Order() int
	// Process handles the request.
	// Call next() to continue the chain.
	Process(ctx fiber.Ctx) error
}

Middleware represents a processing step in the request pipeline.

type Operation added in v0.18.0

type Operation struct {
	// Identifier contains the full operation identity.
	Identifier

	// EnableAudit indicates whether audit logging is enabled.
	EnableAudit bool
	// Timeout is the final timeout duration.
	Timeout time.Duration
	// Auth indicates the authentication configuration.
	Auth *AuthConfig
	// RateLimit is the final rate limit configuration.
	RateLimit *RateLimitConfig
	// Handler is the resolved handler (before adaptation).
	Handler any
	// Dynamic indicates whether this operation is registered dynamically.
	Dynamic bool
	// Meta holds additional operation-specific data.
	// For REST: may contain parsed method, path pattern, etc.
	Meta map[string]any
}

Operation is the runtime operation definition. Created by Engine from Resource + OperationSpec.

func (*Operation) HasRateLimit added in v0.18.0

func (o *Operation) HasRateLimit() bool

HasRateLimit returns true if rate limiting is configured.

func (*Operation) RequiresAuth added in v0.18.0

func (o *Operation) RequiresAuth() bool

RequiresAuth returns true if authentication is required.

type OperationSpec added in v0.18.0

type OperationSpec struct {
	// Action is the action name for the Api endpoint
	Action string
	// EnableAudit indicates whether to enable audit logging for this endpoint
	EnableAudit bool
	// Timeout is the request timeout duration
	Timeout time.Duration
	// Public indicates whether this endpoint is publicly accessible
	Public bool
	// PermToken is the permission token required for access
	PermToken string
	// RateLimit represents the rate limit for an Api endpoint
	RateLimit *RateLimitConfig
	// Handler is the business logic handler.
	Handler any
}

OperationSpec defines the specification for an Api endpoint.

type OperationsCollector added in v0.18.0

type OperationsCollector interface {
	// Collect gathers all operation specs from a resource.
	// Returns specs from embedded OperationsProviders.
	Collect(resource Resource) []OperationSpec
}

OperationsCollector collects all operations from a resource. This includes operations from embedded providers.

type OperationsProvider added in v0.18.0

type OperationsProvider interface {
	// Provide returns the operation specs for this provider.
	Provide() []OperationSpec
}

OperationsProvider provides operation specs. Embed types implementing this interface in a resource to contribute operations.

type P added in v0.7.0

type P struct{}

P is a sentinel type that marks a struct as API parameters. Embed this type in your request parameter struct to enable automatic decoding from Request.Params.

Example:

type CreateUserParams struct {
    api.P
    Name  string `json:"name" validate:"required"`
    Email string `json:"email" validate:"required,email"`
}

type Params

type Params map[string]any

Params holds API request parameters.

func (Params) Decode added in v0.7.0

func (p Params) Decode(out any) error

Decode decodes params into a struct.

type RateLimitConfig added in v0.18.0

type RateLimitConfig struct {
	// Max is the maximum number of requests allowed.
	Max int
	// Period is the time window for rate limiting.
	Period time.Duration
	// Key is a custom rate limit key template.
	// Empty means using the default key.
	Key string
}

RateLimitConfig defines rate limiting configuration.

type Request

type Request struct {
	Identifier

	Params Params `json:"params"`
	Meta   Meta   `json:"meta"`
}

Request represents a unified API request.

func (*Request) GetMeta

func (r *Request) GetMeta(key string) (any, bool)

GetMeta retrieves a value from the request metadata by key.

func (*Request) GetParam

func (r *Request) GetParam(key string) (any, bool)

GetParam retrieves a value from the request params by key.

type Resource

type Resource interface {
	// Kind returns the resource kind.
	Kind() Kind
	// Name returns the resource name (e.g., "users", "sys/config").
	Name() string
	// Version returns the resource version.
	// Empty string means using Engine's default version.
	Version() string
	// Auth returns the resource authentication configuration.
	Auth() *AuthConfig
	// Operations returns the resource operations.
	Operations() []OperationSpec
}

Resource defines an API resource that groups related operations.

func NewRESTResource added in v0.18.0

func NewRESTResource(name string, opts ...ResourceOption) Resource

NewRESTResource creates a new REST resource with the given name and options.

func NewRPCResource added in v0.18.0

func NewRPCResource(name string, opts ...ResourceOption) Resource

NewRPCResource creates a new baseResource with the given name and options.

type ResourceOption added in v0.18.0

type ResourceOption func(*baseResource)

ResourceOption configures a baseResource.

func WithAuth added in v0.18.0

func WithAuth(auth *AuthConfig) ResourceOption

WithAuth sets the resource authentication configuration.

func WithOperations added in v0.18.0

func WithOperations(ops ...OperationSpec) ResourceOption

WithOperations sets the resource operations.

func WithVersion

func WithVersion(v string) ResourceOption

WithVersion sets the resource version.

type RouterStrategy added in v0.18.0

type RouterStrategy interface {
	// Name returns the strategy identifier for logging/debugging.
	Name() string
	// CanHandle returns true if the router can handle the given resource kind.
	CanHandle(kind Kind) bool
	// Setup initializes the router (called once during Mount).
	// Implementations should store the router if needed for Route calls.
	Setup(router fiber.Router) error
	// Route registers an operation with the router.
	Route(handler fiber.Handler, op *Operation)
}

RouterStrategy determines how API operations are exposed as HTTP endpoints.

Jump to

Keyboard shortcuts

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