api

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

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

Auth strategy constants.

View Source
const (
	HeaderXAppID      = "X-App-ID"
	HeaderXTimestamp  = "X-Timestamp"
	HeaderXNonce      = "X-Nonce"
	HeaderXSignature  = "X-Signature"
	HeaderXMetaPrefix = "X-Meta-"
)

HTTP header keys used by the framework.

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

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

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

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

func NewAuditEvent(params AuditEventParams) *AuditEvent

NewAuditEvent creates a new audit event with the given parameters.

type AuditEventParams

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

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

func BearerAuth() *AuthConfig

BearerAuth creates an AuthConfig for BearerAuth token authentication.

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 Kind

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

func (Kind) String

func (k Kind) String() string

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 Meta

type Meta map[string]any

Meta holds API request metadata.

func (Meta) Decode

func (m Meta) Decode(out any) error

Decode decodes meta into a struct.

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
	// 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

func (o *Operation) HasRateLimit() bool

HasRateLimit returns true if rate limiting is configured.

func (*Operation) RequiresAuth

func (o *Operation) RequiresAuth() bool

RequiresAuth returns true if authentication is required.

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
	// 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

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 Params

type Params map[string]any

Params holds API request parameters.

func (Params) Decode

func (p Params) Decode(out any) error

Decode decodes params into a struct.

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.

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

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.

func WithVersion

func WithVersion(v string) ResourceOption

WithVersion sets the resource version.

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.

Jump to

Keyboard shortcuts

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