Documentation
¶
Index ¶
- Constants
- Variables
- func BridgeMiddleware(bridge *Bridge) func(http.Handler) http.Handler
- func BridgeScripts(config ScriptConfig) g.Node
- func BridgeScriptsExternal(config ScriptConfig) g.Node
- func GenerateCSRFToken() (string, error)
- func GetAlpineJS() string
- func GetBridgeJS() string
- func GetClientIP(r *http.Request) string
- func ScriptTemplate(tmpl string, data any) (g.Node, error)
- func SetCSRFCookie(w http.ResponseWriter, token string, cookieName string)
- func ValidateAlphanumeric(value string) error
- func ValidateEmail(email string) error
- func ValidateFloatRange(value, minValue, maxValue float64) error
- func ValidateInput(input string) error
- func ValidateLength(value string, minLength, maxLength int) error
- func ValidateOneOf(value string, allowed []string) error
- func ValidatePattern(value, pattern string) error
- func ValidateRange(value, minValue, maxValue int) error
- func ValidateRequired(value string) error
- func ValidateSlug(slug string) error
- func ValidateURL(url string) error
- func WithBridgeContext(ctx context.Context, bridgeCtx Context) context.Context
- func WriteSSE(w http.ResponseWriter, event StreamEvent) error
- type BatchRequest
- type BatchResponse
- type Bridge
- func (b *Bridge) Call(ctx Context, funcName string, params json.RawMessage) (any, error)
- func (b *Bridge) CallBatch(ctx Context, requests []Request) []Response
- func (b *Bridge) FunctionCount() int
- func (b *Bridge) GetConfig() *Config
- func (b *Bridge) GetFunction(name string) (*Function, error)
- func (b *Bridge) GetFunctionInfo(name string) (*FunctionInfo, error)
- func (b *Bridge) GetHooks() *HookManager
- func (b *Bridge) Handler() http.Handler
- func (b *Bridge) HasFunction(name string) bool
- func (b *Bridge) IntrospectionHandler() http.Handler
- func (b *Bridge) ListFunctionInfo() []FunctionInfo
- func (b *Bridge) ListFunctions() []string
- func (b *Bridge) Register(name string, handler any, opts ...FunctionOption) error
- func (b *Bridge) StreamHandler() http.Handler
- func (b *Bridge) Unregister(name string) error
- type Cache
- type Config
- type ConfigOption
- func WithAllowedOrigins(origins ...string) ConfigOption
- func WithCORS(enabled bool) ConfigOption
- func WithCSRF(enabled bool) ConfigOption
- func WithCache(enabled bool) ConfigOption
- func WithDefaultRateLimit(rpm int) ConfigOption
- func WithMaxBatchSize(size int) ConfigOption
- func WithTimeout(d time.Duration) ConfigOption
- type Context
- type Error
- type Event
- type ExecuteResult
- type FieldInfo
- type Function
- type FunctionInfo
- type FunctionOption
- type HTTPHandler
- type Hook
- type HookData
- type HookManager
- type HookType
- type Integration
- type IntrospectionHandler
- type MemoryCache
- type Middleware
- type RateLimiter
- type Request
- type Response
- type SSEHandler
- type ScriptConfig
- type Security
- type Session
- type SimpleSession
- type SimpleUser
- type StreamChunk
- type StreamEvent
- type TypeInfo
- type User
- type WSHandler
Constants ¶
const ( ErrCodeParseError = -32700 ErrCodeInvalidRequest = -32600 ErrCodeMethodNotFound = -32601 ErrCodeInvalidParams = -32602 ErrCodeInternal = -32603 )
Standard JSON-RPC 2.0 error codes
const ( ErrCodeRateLimit = -32002 ErrCodeTimeout = -32003 ErrCodeBadRequest = -32004 ErrCodeForbidden = -32005 )
Custom error codes
Variables ¶
var ( ErrParseError = NewError(ErrCodeParseError, "Parse error") ErrInvalidRequest = NewError(ErrCodeInvalidRequest, "Invalid request") ErrMethodNotFound = NewError(ErrCodeMethodNotFound, "Method not found") ErrInvalidParams = NewError(ErrCodeInvalidParams, "Invalid params") ErrInternal = NewError(ErrCodeInternal, "Internal error") ErrRateLimit = NewError(ErrCodeRateLimit, "Rate limit exceeded") ErrTimeout = NewError(ErrCodeTimeout, "Request timeout") ErrBadRequest = NewError(ErrCodeBadRequest, "Bad request") ErrForbidden = NewError(ErrCodeForbidden, "Forbidden") )
Common error constructors
Functions ¶
func BridgeMiddleware ¶
BridgeMiddleware creates a standard http.Handler middleware
func BridgeScripts ¶
func BridgeScripts(config ScriptConfig) g.Node
BridgeScripts returns script tags for the bridge client
func BridgeScriptsExternal ¶
func BridgeScriptsExternal(config ScriptConfig) g.Node
BridgeScriptsExternal returns script tags referencing external files
func GenerateCSRFToken ¶
GenerateCSRFToken generates a new CSRF token
func GetAlpineJS ¶
func GetAlpineJS() string
GetAlpineJS returns the Alpine integration JavaScript code
func GetClientIP ¶
GetClientIP extracts the client IP from the request
func ScriptTemplate ¶
ScriptTemplate generates a custom script with configuration
func SetCSRFCookie ¶
func SetCSRFCookie(w http.ResponseWriter, token string, cookieName string)
SetCSRFCookie sets the CSRF token cookie
func ValidateAlphanumeric ¶
ValidateAlphanumeric validates that a string contains only alphanumeric characters
func ValidateEmail ¶
ValidateEmail validates an email address
func ValidateFloatRange ¶
ValidateFloatRange validates that a float is within a range
func ValidateInput ¶
ValidateInput performs basic input sanitization
func ValidateLength ¶
ValidateLength validates string length
func ValidateOneOf ¶
ValidateOneOf validates that a value is one of the allowed values
func ValidatePattern ¶
ValidatePattern validates that a string matches a pattern
func ValidateRange ¶
ValidateRange validates that a number is within a range
func ValidateRequired ¶
ValidateRequired validates that a value is not empty
func WithBridgeContext ¶
WithBridgeContext adds a bridge context to a context.Context
func WriteSSE ¶
func WriteSSE(w http.ResponseWriter, event StreamEvent) error
WriteSSE writes an SSE event
Types ¶
type BatchRequest ¶
type BatchRequest []Request
BatchRequest represents multiple requests in a single call
type Bridge ¶
type Bridge struct {
// contains filtered or unexported fields
}
Bridge manages function registration and execution
func New ¶
func New(opts ...ConfigOption) *Bridge
New creates a new Bridge with the given configuration
func WithBridgeCache ¶
WithBridgeCache adds caching to a bridge
func (*Bridge) Call ¶
Call executes a function and returns the result This is a high-level method that handles all execution logic
func (*Bridge) FunctionCount ¶
FunctionCount returns the number of registered functions
func (*Bridge) GetFunction ¶
GetFunction retrieves a registered function
func (*Bridge) GetFunctionInfo ¶
func (b *Bridge) GetFunctionInfo(name string) (*FunctionInfo, error)
GetFunctionInfo returns information about a specific function
func (*Bridge) GetHooks ¶
func (b *Bridge) GetHooks() *HookManager
GetHooks returns the hook manager
func (*Bridge) HasFunction ¶
HasFunction checks if a function is registered
func (*Bridge) IntrospectionHandler ¶
IntrospectionHandler returns an HTTP handler for function introspection
func (*Bridge) ListFunctionInfo ¶
func (b *Bridge) ListFunctionInfo() []FunctionInfo
ListFunctionInfo returns information about all registered functions
func (*Bridge) ListFunctions ¶
ListFunctions returns all registered function names
func (*Bridge) Register ¶
func (b *Bridge) Register(name string, handler any, opts ...FunctionOption) error
Register registers a new function Expected signature: func(Context, InputType) (OutputType, error)
func (*Bridge) StreamHandler ¶
StreamHandler returns an SSE handler for the bridge
func (*Bridge) Unregister ¶
Unregister removes a function
type Cache ¶
type Cache interface {
// Get retrieves a cached value
Get(key string) (any, bool)
// Set stores a value with TTL
Set(key string, value any, ttl time.Duration)
// Delete removes a cached value
Delete(key string)
// Clear removes all cached values
Clear()
}
Cache provides result caching
type Config ¶
type Config struct {
// Timeout is the default timeout for function execution
Timeout time.Duration
// MaxBatchSize is the maximum number of requests in a batch
MaxBatchSize int
// EnableCSRF enables CSRF token validation
EnableCSRF bool
// EnableCORS enables CORS headers
EnableCORS bool
// AllowedOrigins is the list of allowed origins for CORS
AllowedOrigins []string
// DefaultRateLimit is the default rate limit (requests per minute)
DefaultRateLimit int
// EnableCache enables result caching
EnableCache bool
// CSRFTokenHeader is the header name for CSRF token
CSRFTokenHeader string
// CSRFCookieName is the cookie name for CSRF token
CSRFCookieName string
}
Config holds bridge configuration
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns the default bridge configuration
type ConfigOption ¶
type ConfigOption func(*Config)
ConfigOption configures the Bridge
func WithAllowedOrigins ¶
func WithAllowedOrigins(origins ...string) ConfigOption
WithAllowedOrigins sets the allowed origins for CORS
func WithCSRF ¶
func WithCSRF(enabled bool) ConfigOption
WithCSRF enables or disables CSRF protection
func WithDefaultRateLimit ¶
func WithDefaultRateLimit(rpm int) ConfigOption
WithDefaultRateLimit sets the default rate limit
func WithMaxBatchSize ¶
func WithMaxBatchSize(size int) ConfigOption
WithMaxBatchSize sets the maximum batch size
func WithTimeout ¶
func WithTimeout(d time.Duration) ConfigOption
WithTimeout sets the default timeout
type Context ¶
type Context interface {
// Context returns the underlying context.Context
Context() context.Context
// Request returns the HTTP request
Request() *http.Request
// Value retrieves a value from the context
Value(key any) any
// Session returns session data (implementation-specific)
Session() Session
// User returns the authenticated user (if any)
User() User
// SetValue stores a value in the context
SetValue(key, val any)
}
Context provides access to request-scoped data
func GetBridgeContext ¶
GetBridgeContext retrieves a bridge context from context.Context
func WithSession ¶
WithSession returns a new context with the given session
type Error ¶
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
Error represents a JSON-RPC 2.0 error
type ExecuteResult ¶
ExecuteResult holds the result of a function execution
type FieldInfo ¶
type FieldInfo struct {
Name string `json:"name"`
Type string `json:"type"`
JSONName string `json:"jsonName"`
Required bool `json:"required"`
}
FieldInfo describes a struct field
type Function ¶
type Function struct {
// Name is the function's registered name
Name string
// Handler is the actual function to call
Handler reflect.Value
// InputType is the type of the input parameter
InputType reflect.Type
// OutputType is the type of the output value
OutputType reflect.Type
// Description is the function's documentation
Description string
// RequireAuth indicates if authentication is required
RequireAuth bool
// RequireRoles specifies required user roles
RequireRoles []string
// Timeout is the maximum execution time
Timeout time.Duration
// RateLimit is the max requests per minute (0 = no limit)
RateLimit int
// Cacheable indicates if results can be cached
Cacheable bool
// CacheTTL is the cache time-to-live
CacheTTL time.Duration
}
Function represents a registered bridge function
func (*Function) GetTypeInfo ¶
GetTypeInfo returns type information for the function
type FunctionInfo ¶
type FunctionInfo struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
RequireAuth bool `json:"requireAuth"`
RequireRoles []string `json:"requireRoles,omitempty"`
RateLimit int `json:"rateLimit,omitempty"`
TypeInfo TypeInfo `json:"typeInfo"`
}
FunctionInfo contains information about a registered function
type FunctionOption ¶
type FunctionOption func(*Function)
FunctionOption configures a Function
func RequireAuth ¶
func RequireAuth() FunctionOption
RequireAuth marks a function as requiring authentication
func RequireRoles ¶
func RequireRoles(roles ...string) FunctionOption
RequireRoles specifies required user roles
func WithDescription ¶
func WithDescription(desc string) FunctionOption
WithDescription sets the function description
func WithFunctionCache ¶
func WithFunctionCache(ttl time.Duration) FunctionOption
WithFunctionCache enables result caching for a function
func WithFunctionTimeout ¶
func WithFunctionTimeout(d time.Duration) FunctionOption
WithFunctionTimeout sets a custom timeout for a function
func WithRateLimit ¶
func WithRateLimit(rpm int) FunctionOption
WithRateLimit sets a rate limit (requests per minute)
type HTTPHandler ¶
type HTTPHandler struct {
// contains filtered or unexported fields
}
HTTPHandler implements http.Handler for bridge requests
func NewHTTPHandler ¶
func NewHTTPHandler(bridge *Bridge) *HTTPHandler
NewHTTPHandler creates a new HTTP handler
func (*HTTPHandler) ServeHTTP ¶
func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP handles HTTP requests
type HookData ¶
type HookData struct {
FunctionName string
Params any
Result any
Error error
Duration int64 // Execution time in microseconds
}
HookData contains information passed to hooks
type HookManager ¶
type HookManager struct {
// contains filtered or unexported fields
}
HookManager manages hooks
func (*HookManager) Clear ¶
func (hm *HookManager) Clear(hookType HookType)
Clear removes all hooks of the given type
func (*HookManager) Count ¶
func (hm *HookManager) Count(hookType HookType) int
Count returns the number of hooks for a given type
func (*HookManager) Register ¶
func (hm *HookManager) Register(hookType HookType, hook Hook)
Register adds a hook for the given type
type HookType ¶
type HookType string
HookType identifies different hook points
const ( // BeforeCall is called before function execution BeforeCall HookType = "before_call" // AfterCall is called after function execution AfterCall HookType = "after_call" // OnError is called when an error occurs OnError HookType = "on_error" // OnSuccess is called when a function succeeds OnSuccess HookType = "on_success" )
type Integration ¶
type Integration struct {
// contains filtered or unexported fields
}
Integration provides ForgeUI integration helpers
func NewIntegration ¶
func NewIntegration(bridge *Bridge) *Integration
NewIntegration creates a new ForgeUI integration
func (*Integration) RegisterHTTPRoutes ¶
func (i *Integration) RegisterHTTPRoutes(mux *http.ServeMux)
RegisterHTTPRoutes registers bridge routes with standard http.ServeMux
type IntrospectionHandler ¶
type IntrospectionHandler struct {
// contains filtered or unexported fields
}
IntrospectionHandler handles introspection requests
func NewIntrospectionHandler ¶
func NewIntrospectionHandler(bridge *Bridge) *IntrospectionHandler
NewIntrospectionHandler creates a new introspection handler
func (*IntrospectionHandler) ServeHTTP ¶
func (h *IntrospectionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP handles introspection HTTP requests
type MemoryCache ¶
type MemoryCache struct {
// contains filtered or unexported fields
}
MemoryCache is an in-memory cache implementation
func (*MemoryCache) Count ¶
func (c *MemoryCache) Count() int
Count returns the number of cached items
type Middleware ¶
Middleware wraps an http.Handler with additional functionality
func CORSMiddleware ¶
func CORSMiddleware(allowedOrigins []string) Middleware
CORSMiddleware adds CORS headers
func RecoveryMiddleware ¶
func RecoveryMiddleware() Middleware
RecoveryMiddleware recovers from panics
func RequestIDMiddleware ¶
func RequestIDMiddleware() Middleware
RequestIDMiddleware adds a unique request ID
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements token bucket rate limiting
func NewRateLimiter ¶
func NewRateLimiter(rate, burst int) *RateLimiter
NewRateLimiter creates a new rate limiter
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(key string) bool
Allow checks if a request is allowed for the given key
func (*RateLimiter) Count ¶
func (rl *RateLimiter) Count() int
Count returns the number of active buckets
func (*RateLimiter) Remaining ¶
func (rl *RateLimiter) Remaining(key string) int
Remaining returns the number of tokens remaining for a key
func (*RateLimiter) Reset ¶
func (rl *RateLimiter) Reset(key string)
Reset resets the rate limit for a key
type Request ¶
type Request struct {
JSONRPC string `json:"jsonrpc"`
ID any `json:"id,omitempty"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
Request represents a JSON-RPC 2.0 request
type Response ¶
type Response struct {
JSONRPC string `json:"jsonrpc"`
ID any `json:"id,omitempty"`
Result any `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
}
Response represents a JSON-RPC 2.0 response
type SSEHandler ¶
type SSEHandler struct {
// contains filtered or unexported fields
}
SSEHandler handles Server-Sent Events streaming
func NewSSEHandler ¶
func NewSSEHandler(bridge *Bridge) *SSEHandler
NewSSEHandler creates a new SSE handler
func (*SSEHandler) ServeHTTP ¶
func (h *SSEHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP handles SSE requests
type ScriptConfig ¶
ScriptConfig configures the bridge scripts
type Security ¶
type Security struct {
// contains filtered or unexported fields
}
Security handles authentication, authorization, and CSRF
func NewSecurity ¶
NewSecurity creates a new security instance
type Session ¶
type Session interface {
// Get retrieves a value from the session
Get(key string) (any, bool)
// Set stores a value in the session
Set(key string, value any)
// ID returns the session ID
ID() string
// Delete removes a value from the session
Delete(key string)
// Clear removes all values from the session
Clear()
}
Session represents user session data
type SimpleSession ¶
type SimpleSession struct {
SessionID string
// contains filtered or unexported fields
}
SimpleSession is a basic implementation of Session
func NewSimpleSession ¶
func NewSimpleSession(id string) *SimpleSession
NewSimpleSession creates a new simple session
func (*SimpleSession) Clear ¶
func (s *SimpleSession) Clear()
Clear removes all values from the session
func (*SimpleSession) Delete ¶
func (s *SimpleSession) Delete(key string)
Delete removes a value from the session
func (*SimpleSession) Get ¶
func (s *SimpleSession) Get(key string) (any, bool)
Get retrieves a value from the session
func (*SimpleSession) Set ¶
func (s *SimpleSession) Set(key string, value any)
Set stores a value in the session
type SimpleUser ¶
type SimpleUser struct {
UserID string `json:"id"`
UserEmail string `json:"email"`
UserName string `json:"name"`
UserRoles []string `json:"roles"`
UserData map[string]any `json:"data"`
}
SimpleUser is a basic implementation of User
func (*SimpleUser) Data ¶
func (u *SimpleUser) Data() map[string]any
Data returns additional user data
func (*SimpleUser) Email ¶
func (u *SimpleUser) Email() string
Email returns the user's email address
func (*SimpleUser) HasRole ¶
func (u *SimpleUser) HasRole(role string) bool
HasRole checks if the user has a specific role
func (*SimpleUser) Roles ¶
func (u *SimpleUser) Roles() []string
Roles returns the user's roles/permissions
type StreamChunk ¶
type StreamChunk struct {
Data any `json:"data,omitempty"`
Error *Error `json:"error,omitempty"`
Done bool `json:"done"`
}
StreamChunk represents a chunk of streaming data
type StreamEvent ¶
type StreamEvent struct {
Event string `json:"event,omitempty"`
Data any `json:"data"`
ID string `json:"id,omitempty"`
}
StreamEvent sends an event to SSE clients
type TypeInfo ¶
type TypeInfo struct {
Name string `json:"name"`
InputType string `json:"inputType"`
OutputType string `json:"outputType"`
Fields []FieldInfo `json:"fields,omitempty"`
}
TypeInfo returns information about the function's types
type User ¶
type User interface {
// ID returns the user's unique identifier
ID() string
// Email returns the user's email address
Email() string
// Name returns the user's display name
Name() string
// Roles returns the user's roles/permissions
Roles() []string
// HasRole checks if the user has a specific role
HasRole(role string) bool
// Data returns additional user data
Data() map[string]any
}
User represents an authenticated user
type WSHandler ¶
type WSHandler struct {
// contains filtered or unexported fields
}
WSHandler handles WebSocket connections
func NewWSHandler ¶
NewWSHandler creates a new WebSocket handler
func (*WSHandler) SendToUser ¶
SendToUser sends a message to a specific user