bridge

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: MIT Imports: 25 Imported by: 0

README

ForgeUI Bridge System

Go-JavaScript Bridge for calling server-side Go functions from client-side JavaScript

Overview

The ForgeUI Bridge provides a seamless way to call Go functions from JavaScript without writing custom API endpoints. It supports:

  • HTTP (JSON-RPC 2.0): Single and batch requests
  • WebSocket: Real-time bidirectional communication
  • Server-Sent Events (SSE): Server-to-client streaming
  • Type Safety: Automatic parameter validation
  • Security: Built-in CSRF protection, rate limiting, and authentication
  • Alpine.js Integration: Magic helpers and directives

Quick Start

Server Side (Go)
package main

import (
	"github.com/xraph/forgeui/bridge"
	"github.com/xraph/forgeui/router"
)

func main() {
	// Create bridge
	b := bridge.New()

	// Register functions
	b.Register("greet", func(ctx bridge.Context, input struct {
		Name string `json:"name"`
	}) (struct {
		Message string `json:"message"`
	}, error) {
		return struct {
			Message string `json:"message"`
		}{Message: "Hello, " + input.Name}, nil
	})

	// Create router and enable bridge
	r := router.New()
	bridge.EnableBridge(r, b)

	// Start server
	http.ListenAndServe(":8080", r)
}
Client Side (JavaScript)
<!DOCTYPE html>
<html>
<head>
	<script src="https://unpkg.com/alpinejs@3" defer></script>
</head>
<body>
	<!-- Include bridge scripts -->
	<!-- Generated by bridge.BridgeScripts() -->

	<div x-data="{ name: '', greeting: '' }">
		<input x-model="name" placeholder="Your name">
		<button @click="greeting = await $bridge.call('greet', { name })">
			Greet
		</button>
		<p x-text="greeting"></p>
	</div>
</body>
</html>

Features

1. Function Registration

Register any Go function that matches the signature:

func(ctx bridge.Context, input InputType) (OutputType, error)

Example:

type CreateTodoInput struct {
	Title string `json:"title"`
	Done  bool   `json:"done"`
}

type Todo struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
	Done  bool   `json:"done"`
}

b.Register("createTodo", func(ctx bridge.Context, input CreateTodoInput) (*Todo, error) {
	// Create todo in database
	todo := &Todo{
		ID:    generateID(),
		Title: input.Title,
		Done:  input.Done,
	}
	
	return todo, nil
})
2. Function Options

Customize function behavior with options:

b.Register("adminAction", handler,
	bridge.RequireAuth(),                    // Require authentication
	bridge.RequireRoles("admin"),            // Require specific roles
	bridge.WithTimeout(10*time.Second),      // Custom timeout
	bridge.WithRateLimit(10),                // Rate limit (requests/min)
	bridge.WithCache(5*time.Minute),         // Cache results
	bridge.WithDescription("Admin action"),  // Documentation
)
3. Authentication & Authorization
// Require authentication
b.Register("protected", handler, bridge.RequireAuth())

// Require specific roles
b.Register("adminOnly", handler, 
	bridge.RequireAuth(),
	bridge.RequireRoles("admin", "superuser"),
)

// Access user in function
func handler(ctx bridge.Context, input InputType) (OutputType, error) {
	user := ctx.User()
	if user == nil {
		return nil, bridge.ErrUnauthorized
	}
	
	// Use user information
	userID := user.ID()
	// ...
}
4. JavaScript Client
Basic Usage
const bridge = new ForgeBridge({
	endpoint: '/api/bridge',
	timeout: 30000,
	csrf: document.cookie.match(/csrf_token=([^;]+)/)?.[1]
});

// Single call
const result = await bridge.call('functionName', { param: 'value' });

// Batch call
const results = await bridge.callBatch([
	{ method: 'func1', params: { a: 1 } },
	{ method: 'func2', params: { b: 2 } }
]);

// Streaming
const cleanup = bridge.stream('longRunning', {},
	(data) => console.log('Progress:', data),
	(error) => console.error('Error:', error)
);
Alpine.js Integration
<!-- Magic helper -->
<button @click="result = await $bridge.call('functionName', { param: value })">
	Call Function
</button>

<!-- Directive -->
<button x-bridge.click="greet:{name}">
	Greet
</button>

<!-- Store -->
<div x-data>
	<button @click="$store.bridge.call('getData', {})">
		Load Data
	</button>
	<div x-show="$store.bridge.loading">Loading...</div>
	<div x-show="$store.bridge.error" x-text="$store.bridge.error"></div>
</div>
5. Security
CSRF Protection
// Enable CSRF (default: enabled)
b := bridge.New(bridge.WithCSRF(true))

// Generate token
token, _ := bridge.GenerateCSRFToken()

// Set cookie
bridge.SetCSRFCookie(w, token, "csrf_token")
Rate Limiting
// Global rate limit
b := bridge.New(bridge.WithDefaultRateLimit(60)) // 60 req/min

// Per-function rate limit
b.Register("func", handler, bridge.WithRateLimit(10)) // 10 req/min
Input Validation
// Automatic validation from struct tags
type Input struct {
	Email    string `json:"email" validate:"email"`
	Age      int    `json:"age" validate:"range:0,150"`
	Username string `json:"username" validate:"required"`
}

// Custom validators
if err := bridge.ValidateEmail(email); err != nil {
	return nil, err
}

if err := bridge.ValidateRange(age, 0, 150); err != nil {
	return nil, err
}
6. Transports
HTTP (JSON-RPC 2.0)

Default transport for single and batch requests.

// Automatically registered at:
// POST /api/bridge
// POST /api/bridge/batch
WebSocket

For real-time bidirectional communication.

// Automatically registered at:
// GET /api/bridge/ws

// Broadcast to all clients
wsHandler := bridge.NewWSHandler(b)
wsHandler.Broadcast(bridge.Event{
	Type: "notification",
	Data: "Hello everyone!",
})

// Send to specific user
wsHandler.SendToUser(userID, bridge.Event{
	Type: "message",
	Data: "Personal message",
})
Server-Sent Events (SSE)

For server-to-client streaming.

// Automatically registered at:
// GET /api/bridge/stream?method=funcName&params=...
7. Hooks

Execute code before/after function calls:

// Before call
b.GetHooks().Register(bridge.BeforeCall, func(ctx bridge.Context, data bridge.HookData) {
	log.Printf("Calling %s with params: %v", data.FunctionName, data.Params)
})

// After call
b.GetHooks().Register(bridge.AfterCall, func(ctx bridge.Context, data bridge.HookData) {
	log.Printf("Function %s took %dμs", data.FunctionName, data.Duration)
})

// On error
b.GetHooks().Register(bridge.OnError, func(ctx bridge.Context, data bridge.HookData) {
	log.Printf("Error in %s: %v", data.FunctionName, data.Error)
})

// On success
b.GetHooks().Register(bridge.OnSuccess, func(ctx bridge.Context, data bridge.HookData) {
	log.Printf("Function %s succeeded: %v", data.FunctionName, data.Result)
})
8. Caching
// Enable caching
b := bridge.New(bridge.WithCache(true))

// Cache specific function results
b.Register("expensiveOp", handler, 
	bridge.WithCache(10*time.Minute), // Cache for 10 minutes
)
9. Introspection

List all registered functions and their metadata:

// Automatically registered at:
// GET /api/bridge/functions

// Programmatic access
functions := b.ListFunctionInfo()
for _, fn := range functions {
	fmt.Printf("Function: %s\n", fn.Name)
	fmt.Printf("  Description: %s\n", fn.Description)
	fmt.Printf("  Requires Auth: %v\n", fn.RequireAuth)
	fmt.Printf("  Input Type: %s\n", fn.TypeInfo.InputType)
	fmt.Printf("  Output Type: %s\n", fn.TypeInfo.OutputType)
}

Configuration

Bridge Options
b := bridge.New(
	bridge.WithTimeout(30*time.Second),      // Default timeout
	bridge.WithMaxBatchSize(10),             // Max batch size
	bridge.WithCSRF(true),                   // Enable CSRF
	bridge.WithCORS(true),                   // Enable CORS
	bridge.WithAllowedOrigins("*"),          // Allowed origins
	bridge.WithDefaultRateLimit(60),         // Default rate limit
	bridge.WithCache(true),                  // Enable caching
)
Script Generation
// Inline scripts
html := bridge.BridgeScripts(bridge.ScriptConfig{
	Endpoint:      "/api/bridge",
	CSRFToken:     csrfToken,
	IncludeAlpine: true,
})

// External scripts
html := bridge.BridgeScriptsExternal(bridge.ScriptConfig{
	Endpoint:      "/api/bridge",
	CSRFToken:     csrfToken,
	IncludeAlpine: true,
})

Error Handling

Server Side
func handler(ctx bridge.Context, input Input) (Output, error) {
	if input.Invalid {
		return nil, bridge.NewError(bridge.ErrCodeBadRequest, "Invalid input")
	}
	
	// Or use predefined errors
	if !authorized {
		return nil, bridge.ErrUnauthorized
	}
	
	// Custom error with details
	return nil, bridge.NewError(bridge.ErrCodeBadRequest, "Validation failed", map[string]any{
		"field": "email",
		"reason": "invalid format",
	})
}
Client Side
try {
	const result = await bridge.call('functionName', params);
} catch (err) {
	if (err instanceof BridgeError) {
		console.log('Error code:', err.code);
		console.log('Error message:', err.message);
		console.log('Error data:', err.data);
	}
}

Testing

Unit Tests
func TestMyFunction(t *testing.T) {
	b := bridge.New()
	
	b.Register("myFunc", myHandler)
	
	req := httptest.NewRequest("GET", "/", nil)
	ctx := bridge.NewContext(req)
	
	result, err := b.Call(ctx, "myFunc", json.RawMessage(`{"input":"value"}`))
	if err != nil {
		t.Fatal(err)
	}
	
	// Assert result
}
Integration Tests
func TestBridgeIntegration(t *testing.T) {
	b := bridge.New(bridge.WithCSRF(false))
	b.Register("test", handler)
	
	handler := bridge.NewHTTPHandler(b)
	
	req := bridge.Request{
		JSONRPC: "2.0",
		ID:      "1",
		Method:  "test",
		Params:  json.RawMessage(`{}`),
	}
	
	body, _ := json.Marshal(req)
	httpReq := httptest.NewRequest("POST", "/api/bridge", bytes.NewReader(body))
	w := httptest.NewRecorder()
	
	handler.ServeHTTP(w, httpReq)
	
	// Assert response
}

Performance

  • Overhead: <5ms per request (excluding function execution)
  • Throughput: 1000+ req/s on modest hardware
  • Memory: Minimal footprint with connection pooling
  • JavaScript Bundle: <3KB minified + gzipped

Best Practices

  1. Use meaningful function names: createUser not func1
  2. Validate inputs: Always validate user inputs
  3. Set timeouts: Use appropriate timeouts for long-running functions
  4. Enable rate limiting: Protect against abuse
  5. Use authentication: Protect sensitive functions
  6. Cache expensive operations: Use caching for expensive computations
  7. Handle errors gracefully: Return descriptive error messages
  8. Document functions: Use WithDescription() for API documentation
  9. Test thoroughly: Write unit and integration tests
  10. Monitor performance: Use hooks for logging and monitoring

License

MIT License - See LICENSE file for details

Documentation

Index

Constants

View Source
const (
	ErrCodeParseError     = -32700
	ErrCodeInvalidRequest = -32600
	ErrCodeMethodNotFound = -32601
	ErrCodeInvalidParams  = -32602
	ErrCodeInternal       = -32603
)

Standard JSON-RPC 2.0 error codes

View Source
const (
	ErrCodeUnauthorized = -32001
	ErrCodeRateLimit    = -32002
	ErrCodeTimeout      = -32003
	ErrCodeBadRequest   = -32004
	ErrCodeForbidden    = -32005
)

Custom error codes

Variables

View Source
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")
	ErrUnauthorized   = NewError(ErrCodeUnauthorized, "Unauthorized")
	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

func BridgeMiddleware(bridge *Bridge) func(http.Handler) http.Handler

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

func GenerateCSRFToken() (string, error)

GenerateCSRFToken generates a new CSRF token

func GetAlpineJS

func GetAlpineJS() string

GetAlpineJS returns the Alpine integration JavaScript code

func GetBridgeJS

func GetBridgeJS() string

GetBridgeJS returns the bridge JavaScript code

func GetClientIP

func GetClientIP(r *http.Request) string

GetClientIP extracts the client IP from the request

func ScriptTemplate

func ScriptTemplate(tmpl string, data any) (g.Node, error)

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

func ValidateAlphanumeric(value string) error

ValidateAlphanumeric validates that a string contains only alphanumeric characters

func ValidateEmail

func ValidateEmail(email string) error

ValidateEmail validates an email address

func ValidateFloatRange

func ValidateFloatRange(value, minValue, maxValue float64) error

ValidateFloatRange validates that a float is within a range

func ValidateInput

func ValidateInput(input string) error

ValidateInput performs basic input sanitization

func ValidateLength

func ValidateLength(value string, minLength, maxLength int) error

ValidateLength validates string length

func ValidateOneOf

func ValidateOneOf(value string, allowed []string) error

ValidateOneOf validates that a value is one of the allowed values

func ValidatePattern

func ValidatePattern(value, pattern string) error

ValidatePattern validates that a string matches a pattern

func ValidateRange

func ValidateRange(value, minValue, maxValue int) error

ValidateRange validates that a number is within a range

func ValidateRequired

func ValidateRequired(value string) error

ValidateRequired validates that a value is not empty

func ValidateSlug

func ValidateSlug(slug string) error

ValidateSlug validates a URL-friendly slug

func ValidateURL

func ValidateURL(url string) error

ValidateURL validates a URL

func WithBridgeContext

func WithBridgeContext(ctx context.Context, bridgeCtx Context) context.Context

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 BatchResponse

type BatchResponse []Response

BatchResponse represents multiple responses

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

func WithBridgeCache(b *Bridge, cache Cache) *Bridge

WithBridgeCache adds caching to a bridge

func (*Bridge) Call

func (b *Bridge) Call(ctx Context, funcName string, params json.RawMessage) (any, error)

Call executes a function and returns the result This is a high-level method that handles all execution logic

func (*Bridge) CallBatch

func (b *Bridge) CallBatch(ctx Context, requests []Request) []Response

CallBatch executes multiple functions in parallel

func (*Bridge) FunctionCount

func (b *Bridge) FunctionCount() int

FunctionCount returns the number of registered functions

func (*Bridge) GetConfig

func (b *Bridge) GetConfig() *Config

GetConfig returns the bridge configuration

func (*Bridge) GetFunction

func (b *Bridge) GetFunction(name string) (*Function, error)

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) Handler

func (b *Bridge) Handler() http.Handler

Handler returns an http.Handler for the bridge

func (*Bridge) HasFunction

func (b *Bridge) HasFunction(name string) bool

HasFunction checks if a function is registered

func (*Bridge) IntrospectionHandler

func (b *Bridge) IntrospectionHandler() http.Handler

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

func (b *Bridge) ListFunctions() []string

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

func (b *Bridge) StreamHandler() http.Handler

StreamHandler returns an SSE handler for the bridge

func (*Bridge) Unregister

func (b *Bridge) Unregister(name string) error

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 WithCORS

func WithCORS(enabled bool) ConfigOption

WithCORS enables or disables CORS

func WithCSRF

func WithCSRF(enabled bool) ConfigOption

WithCSRF enables or disables CSRF protection

func WithCache

func WithCache(enabled bool) ConfigOption

WithCache enables or disables caching

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

func GetBridgeContext(ctx context.Context) (Context, bool)

GetBridgeContext retrieves a bridge context from context.Context

func NewContext

func NewContext(r *http.Request) Context

NewContext creates a new bridge context

func WithSession

func WithSession(ctx Context, session Session) Context

WithSession returns a new context with the given session

func WithUser

func WithUser(ctx Context, user User) Context

WithUser returns a new context with the given user

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

func NewError

func NewError(code int, message string, data ...any) *Error

NewError creates a new bridge error

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface

type Event

type Event struct {
	Type string `json:"type"`
	Data any    `json:"data"`
}

Event represents a server-initiated event (for WebSocket/SSE)

type ExecuteResult

type ExecuteResult struct {
	Result any
	Error  *Error
}

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

func (f *Function) GetTypeInfo() TypeInfo

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 Hook

type Hook func(ctx Context, data HookData)

Hook is a function called at specific points in the request lifecycle

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 NewHookManager

func NewHookManager() *HookManager

NewHookManager creates a new hook manager

func (*HookManager) Clear

func (hm *HookManager) Clear(hookType HookType)

Clear removes all hooks of the given type

func (*HookManager) ClearAll

func (hm *HookManager) ClearAll()

ClearAll removes all hooks

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

func (*HookManager) Trigger

func (hm *HookManager) Trigger(hookType HookType, ctx Context, data HookData)

Trigger executes all hooks of 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 NewMemoryCache

func NewMemoryCache() *MemoryCache

NewMemoryCache creates a new memory cache

func (*MemoryCache) Clear

func (c *MemoryCache) Clear()

Clear removes all cached values

func (*MemoryCache) Count

func (c *MemoryCache) Count() int

Count returns the number of cached items

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(key string)

Delete removes a cached value

func (*MemoryCache) Get

func (c *MemoryCache) Get(key string) (any, bool)

Get retrieves a cached value

func (*MemoryCache) Set

func (c *MemoryCache) Set(key string, value any, ttl time.Duration)

Set stores a value with TTL

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware wraps an http.Handler with additional functionality

func CORSMiddleware

func CORSMiddleware(allowedOrigins []string) Middleware

CORSMiddleware adds CORS headers

func Chain

func Chain(middlewares ...Middleware) Middleware

Chain combines multiple middleware

func LoggerMiddleware

func LoggerMiddleware() Middleware

LoggerMiddleware logs HTTP requests

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

type ScriptConfig struct {
	Endpoint      string
	CSRFToken     string
	IncludeAlpine bool
}

ScriptConfig configures the bridge scripts

type Security

type Security struct {
	// contains filtered or unexported fields
}

Security handles authentication, authorization, and CSRF

func NewSecurity

func NewSecurity(config *Config) *Security

NewSecurity creates a new security instance

func (*Security) CheckAuth

func (s *Security) CheckAuth(ctx Context, fn *Function) error

CheckAuth verifies authentication

func (*Security) CheckCSRF

func (s *Security) CheckCSRF(r *http.Request) error

CheckCSRF verifies CSRF token

func (*Security) CheckRateLimit

func (s *Security) CheckRateLimit(key string, fn *Function) error

CheckRateLimit verifies rate limiting

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) ID

func (s *SimpleSession) ID() string

ID returns the session ID

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) ID

func (u *SimpleUser) ID() string

ID returns the user's unique identifier

func (*SimpleUser) Name

func (u *SimpleUser) Name() string

Name returns the user's display name

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

func NewWSHandler(bridge *Bridge) *WSHandler

NewWSHandler creates a new WebSocket handler

func (*WSHandler) Broadcast

func (h *WSHandler) Broadcast(event Event)

Broadcast sends a message to all connected clients

func (*WSHandler) SendToUser

func (h *WSHandler) SendToUser(userID string, event Event)

SendToUser sends a message to a specific user

func (*WSHandler) ServeHTTP

func (h *WSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles WebSocket upgrade requests

Jump to

Keyboard shortcuts

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