Documentation
¶
Index ¶
- Constants
- Variables
- func SubscribeAuditEvent(bus event.Bus, handler func(context.Context, *AuditEvent) error, ...) (event.Unsubscribe, error)
- func ValidateActionName(action string, kind Kind) error
- type AuditEvent
- type AuthConfig
- type AuthStrategy
- type AuthStrategyRegistry
- type Engine
- type FactoryParamResolver
- type HandlerAdapter
- type HandlerParamResolver
- type HandlerResolver
- type Identifier
- type Kind
- type M
- type Meta
- type Middleware
- type Operation
- type OperationSpec
- type OperationsCollector
- type OperationsProvider
- type P
- type Params
- type RateLimitConfig
- type Request
- type Resource
- type ResourceOption
- type RouterStrategy
Constants ¶
const ( AuthStrategyNone = "none" AuthStrategyBearer = "bearer" AuthStrategySignature = "signature" AuthStrategyIP = "ip" )
Auth strategy constants.
const ( HeaderXAppID = "X-App-ID" HeaderXTimestamp = "X-Timestamp" HeaderXNonce = "X-Nonce" HeaderXSignature = "X-Signature" HeaderXMetaPrefix = "X-Meta-" )
HTTP header keys used by the framework.
const ( VersionV1 = "v1" VersionV2 = "v2" VersionV3 = "v3" VersionV4 = "v4" VersionV5 = "v5" VersionV6 = "v6" VersionV7 = "v7" VersionV8 = "v8" VersionV9 = "v9" )
Version vocabulary for declaring a resource's API version via WithVersion. VersionV1 is the framework default; V2..V9 are the reserved version ladder downstream applications use to declare higher API versions (e.g. api.WithVersion(api.VersionV3)). validateVersion also accepts any literal matching ^v\d+$.
const AuthOptionWhitelist = "whitelist"
AuthOptionWhitelist is the AuthConfig.Options key holding the name of the IP whitelist the "ip" strategy authenticates against.
const DefaultIPWhitelist = "default"
DefaultIPWhitelist is the whitelist name IPAuth falls back to when called without an explicit name; configure it as the "default" key under vef.security.ip_whitelists (or serve it from a custom loader).
Variables ¶
var ( ErrInvalidRequestParams = result.Err( i18n.T("api_request_params_invalid_json"), result.WithCode(result.ErrCodeBadRequest), result.WithStatus(fiber.StatusBadRequest), ) ErrInvalidRequestMeta = result.Err( i18n.T("api_request_meta_invalid_json"), result.WithCode(result.ErrCodeBadRequest), result.WithStatus(fiber.StatusBadRequest), ) )
Predefined API request decoding errors. A malformed request (unparseable body, wrong param/meta type) is a client error, so it carries HTTP 400 — matching the validation path, which also returns 400 for the same bad-request code. (Business errors keep HTTP 200 with a code; a malformed request is a transport-level fault, not a business outcome.)
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 ¶
func SubscribeAuditEvent( bus event.Bus, handler func(context.Context, *AuditEvent) error, opts ...event.SubscribeOption, ) (event.Unsubscribe, error)
SubscribeAuditEvent registers a typed handler for audit events.
func ValidateActionName ¶
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 ¶
type AuditEvent struct {
// 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 (*AuditEvent) EventType ¶ added in v0.24.0
func (*AuditEvent) EventType() string
EventType implements event.Event.
type AuthConfig ¶
type AuthConfig struct {
// Strategy specifies the auth strategy name. default is "bearer".
// Built-in: "none", "bearer", "signature", "ip"
// 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 ¶
func BearerAuth() *AuthConfig
BearerAuth creates an AuthConfig for BearerAuth token authentication.
func IPAuth ¶ added in v0.34.0
func IPAuth(whitelistName ...string) *AuthConfig
IPAuth creates an AuthConfig for source-IP whitelist authentication. The request is authenticated when the client IP matches the named whitelist, resolved through the registered security.IPWhitelistLoader (by default the vef.security.ip_whitelists configuration). Call it with no argument to target the DefaultIPWhitelist name, or with exactly one name to target a specific whitelist; passing more than one name panics. The client IP is the one resolved by Fiber, so behind a reverse proxy vef.app.trusted_proxies must be configured for the whitelist to see the real client address.
func Public ¶
func Public() *AuthConfig
Public creates an AuthConfig for public endpoints (no authentication).
func SignatureAuth ¶
func SignatureAuth() *AuthConfig
SignatureAuth creates an AuthConfig for signature-based authentication.
func (*AuthConfig) Clone ¶
func (c *AuthConfig) Clone() *AuthConfig
Clone creates a deep copy of the AuthConfig.
type AuthStrategy ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 M ¶
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 Middleware ¶
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 ¶
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
// 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.
type OperationSpec ¶
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
// RequiredPermission is the permission token required for access
RequiredPermission 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 ¶
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 ¶
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 ¶
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 RateLimitConfig ¶
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.
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 ¶
func NewRESTResource(name string, opts ...ResourceOption) Resource
NewRESTResource creates a new REST resource with the given name and options.
func NewRPCResource ¶
func NewRPCResource(name string, opts ...ResourceOption) Resource
NewRPCResource creates a new baseResource with the given name and options.
type ResourceOption ¶
type ResourceOption func(*baseResource)
ResourceOption configures a baseResource.
func WithAuth ¶
func WithAuth(auth *AuthConfig) ResourceOption
WithAuth sets the resource authentication configuration.
func WithOperations ¶
func WithOperations(ops ...OperationSpec) ResourceOption
WithOperations sets the resource operations.
type RouterStrategy ¶
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.