Documentation
¶
Index ¶
- Constants
- Variables
- func SubscribeAuditEvent(subscriber event.Subscriber, handler func(context.Context, *AuditEvent)) event.UnsubscribeFunc
- func ValidateActionName(action string) error
- func ValidateResourceName(name string) error
- func WithApis(apis ...Spec) resourceOption
- func WithVersion(version string) resourceOption
- type AuditEvent
- type Definition
- type FactoryParamResolver
- type HandlerParamResolver
- type Identifier
- type M
- type Manager
- type Meta
- type P
- type Params
- type Provider
- type RateLimit
- type Request
- type Resource
- type Spec
Constants ¶
const ( VersionV1 = "v1" // v1 is the default version VersionV2 = "v2" VersionV3 = "v3" VersionV4 = "v4" VersionV5 = "v5" VersionV6 = "v6" VersionV7 = "v7" VersionV8 = "v8" VersionV9 = "v9" )
Variables ¶
var ( // ErrResourceNameEmpty is returned when the resource name is empty. ErrResourceNameEmpty = errors.New("resource name cannot be empty") // ErrResourceNameInvalidFormat is returned when the resource name is not in snake_case format. ErrResourceNameInvalidFormat = errors.New("resource name must be in snake_case format with optional slashes") // ErrResourceNameInvalidSlash is returned when the resource name starts or ends with a slash. ErrResourceNameInvalidSlash = errors.New("resource name cannot start or end with a slash") // ErrResourceNameConsecutiveSlashes is returned when the resource name contains consecutive slashes. ErrResourceNameConsecutiveSlashes = errors.New("resource name cannot contain consecutive slashes") // ErrActionNameEmpty is returned when the action name is empty. ErrActionNameEmpty = errors.New("action name cannot be empty") // ErrActionNameInvalidFormat is returned when the action name is not in snake_case format. ErrActionNameInvalidFormat = errors.New("action name must be in snake_case format") // ErrParamsDecodeTypeMismatch is returned when Params.Decode receives a non-pointer or non-struct type. ErrParamsDecodeTypeMismatch = errors.New("Params.Decode requires a pointer to struct") // ErrMetaDecodeTypeMismatch is returned when Meta.Decode receives a non-pointer or non-struct type. ErrMetaDecodeTypeMismatch = errors.New("Meta.Decode requires a 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
ValidateActionName checks if the action name follows snake_case format. Valid examples: "create", "find_page", "get_user_info" Invalid examples: "Create", "findPage", "getUserInfo".
func ValidateResourceName ¶ added in v0.6.0
ValidateResourceName checks if the resource name follows the correct format. Resource names must be in snake_case and can contain slashes for namespacing. Valid examples: "user", "sys/user", "auth/get_user_info" Invalid examples: "User", "sys/User", "sys/getUserInfo", "sys/".
func WithApis ¶ added in v0.6.0
func WithApis(apis ...Spec) resourceOption
WithApis configures the Api endpoints for the resource. It accepts a variadic list of Spec objects that define the available Apis. All action names in the Spec objects must be in snake_case format. Panics if any action name format is invalid.
func WithVersion ¶
func WithVersion(version string) resourceOption
This option allows overriding the default v1 version with a custom version string. The version must match the pattern "v" followed by one or more digits (e.g., v1, v2, v10). Panics if the version format is invalid.
Types ¶
type AuditEvent ¶ added in v0.5.0
type AuditEvent struct {
event.BaseEvent
// Api identification
Resource string `json:"resource"` // Api resource name
Action string `json:"action"` // Api action name
Version string `json:"version"` // Api version
// User identification
UserId string `json:"userId"` // Operating user id
UserAgent string `json:"userAgent"` // User agent (User-Agent header)
// Request information
RequestId string `json:"requestId"` // Request Id
RequestIP string `json:"requestIp"` // Request IP address
RequestParams map[string]any `json:"requestParams"` // Request parameters
RequestMeta map[string]any `json:"requestMeta"` // Request metadata
// Response information
ResultCode int `json:"resultCode"` // Result code (business code)
ResultMessage string `json:"resultMessage"` // Result message
ResultData any `json:"resultData"` // Result data (optional)
// Performance metrics
ElapsedTime int `json:"elapsedTime"` // Elapsed time in milliseconds
}
AuditEvent represents an Api audit log event. It captures comprehensive information about Api requests including request details, user identity, response status, and performance metrics.
func NewAuditEvent ¶ added in v0.5.0
func NewAuditEvent( apiResource, apiAction, apiVersion string, userId, userAgent string, requestId, requestIp string, requestParams, requestMeta map[string]any, resultCode int, resultMessage string, resultData any, elapsedTime int, ) *AuditEvent
NewAuditEvent creates a new audit event with the given parameters.
type Definition ¶
type Definition struct {
Identifier
// 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
// Limit represents the rate limit for an Api endpoint
Limit RateLimit
// Handler is the actual handler function for this endpoint
Handler fiber.Handler
}
Definition represents a complete Api definition with identifier, configuration, and handler.
func (*Definition) GetTimeout ¶
func (d *Definition) GetTimeout() time.Duration
GetTimeout returns the configured timeout or a default value.
func (*Definition) HasRateLimit ¶
func (d *Definition) HasRateLimit() bool
HasRateLimit returns true if the endpoint has a rate limit configured.
func (*Definition) IsPublic ¶
func (d *Definition) IsPublic() bool
IsPublic returns true if the endpoint is publicly accessible.
func (*Definition) RequiresPermission ¶
func (d *Definition) RequiresPermission() bool
RequiresPermission returns true if the endpoint requires a permission token.
type FactoryParamResolver ¶ added in v0.11.0
type FactoryParamResolver interface {
// Type returns the parameter type this resolver handles
Type() reflect.Type
// Resolve returns an instance of the type (as reflect.Value)
// Called during resource registration, resolver should return instances already injected via DI
Resolve() reflect.Value
}
FactoryParamResolver resolves parameters for handler factory functions. Unlike HandlerParamResolver, it executes during resource registration (application startup) and does not depend on a specific HTTP request context.
type HandlerParamResolver ¶
type HandlerParamResolver interface {
Type() reflect.Type
Resolve(ctx fiber.Ctx) (reflect.Value, error)
}
HandlerParamResolver declares a pluggable strategy to resolve a single handler parameter from the current request context. Implementations should be pure and fast, as they are invoked for every handler call.
type Identifier ¶
type Identifier struct {
// The version of the Api endpoint
Version string `json:"version" form:"version" validate:"required,alphanum" label_i18n:"api_request_version"`
// The resource name of the Api endpoint
Resource string `json:"resource" form:"resource" validate:"required,alphanum_us_slash" label_i18n:"api_request_resource"`
// The action name of the Api endpoint
Action string `json:"action" form:"action" validate:"required,alphanum_us" label_i18n:"api_request_action"`
}
Identifier uniquely identifies an Api endpoint. It consists of version, resource name, and action name.
func (Identifier) Equals ¶
func (id Identifier) Equals(other Identifier) bool
Equals checks if two identifiers are equal.
func (Identifier) IsValid ¶
func (id Identifier) IsValid() bool
IsValid checks if the identifier has all required fields.
func (Identifier) String ¶
func (id Identifier) String() string
String returns a string representation of the identifier.
type M ¶ added in v0.7.0
type M struct {
// contains filtered or unexported fields
}
M is a struct that can be used to inject meta into an Api handler.
type Manager ¶
type Manager interface {
// Register adds a new Api definition to the manager.
// Returns an error if an Api with the same identifier already exists.
Register(api *Definition) error
// Remove removes an Api definition by its identifier.
Remove(id Identifier)
// Lookup retrieves an Api definition by its identifier.
// Returns nil if the definition is not found.
Lookup(id Identifier) *Definition
// List returns all registered Api definitions.
List() []*Definition
}
Manager defines the interface for managing Api definitions. It provides methods to register, remove, and lookup Api definitions by their identifiers.
type P ¶ added in v0.7.0
type P struct {
// contains filtered or unexported fields
}
P is a struct that can be used to inject parameters into an Api handler.
type Provider ¶
type Provider interface {
// Provide returns an Api specification.
Provide() Spec
}
Provider defines the interface for providing Api specifications. It provides a method to generate or retrieve Api specifications.
type RateLimit ¶
type RateLimit struct {
// Max is the rate limit per time window (0 means no limit)
Max int
// Expiration is the rate limit expiration time
Expiration time.Duration
}
RateLimit represents the rate limit for an Api endpoint.
type Request ¶
type Request struct {
Identifier
// The params of the request
Params Params `json:"params"`
// The meta of the request
Meta Meta `json:"meta"`
}
Request represents an Api request with identifier, params, and metadata.
type Resource ¶
type Resource interface {
// Version returns the version of the resource.
Version() string
// Name returns the name of the resource.
Name() string
// Apis returns the list of Api specifications for this resource.
Apis() []Spec
}
Resource represents an Api resource that contains multiple Api specifications. It defines the version, name, and list of Api specifications for a resource.
func NewResource ¶
NewResource creates a new resource with the given name and optional configuration. It initializes the resource with version v1 by default and applies any provided options. The resource name must be in snake_case format and can contain slashes for namespacing. Panics if the resource name format is invalid.
type Spec ¶
type Spec struct {
// Action is the action name for the Api endpoint
Action string
// Version is the version of the Api endpoint
Version 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
// Limit represents the rate limit for an Api endpoint
Limit RateLimit
// Handler is optional. If not provided, the system will automatically search for a method
// in the struct using the Action name converted to PascalCase format.
// The search supports both direct methods and methods from embedded anonymous structs.
// For example, if Action is "create_user", the system will look for "CreateUser" method.
// The handler function should be compatible with the Api framework's handler signature.
Handler any
}
Spec defines the specification for an Api endpoint.