lugo

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2024 License: MIT Imports: 18 Imported by: 0

README ΒΆ

Lugo

Build Status Go Reference Go Report Card License

Lugo is a production-ready Go library for embedding Lua configurations with strong type safety, sandboxing, and seamless Go integration. It provides a robust solution for applications that need dynamic configuration, scripting, or business rule execution while maintaining type safety and security.

🌟 Key Features

  • πŸ”’ Type-Safe Configuration: Define configurations using Go structs and access them with full type safety
  • 🎯 Simple API: Easy-to-use interface for registering types and functions
  • πŸ›‘οΈ Sandboxing: Fine-grained control over script capabilities and resource usage
  • πŸ”Œ Go Function Integration: Expose Go functions to Lua scripts with automatic type conversion
  • ⏱️ Context Support: Built-in support for timeouts and cancellation
  • πŸ”„ Middleware System: Add cross-cutting concerns like logging or metrics
  • πŸͺ Hook System: Monitor and interact with configuration loading and execution
  • πŸš€ Production Ready: Thread-safe, well-tested, and battle-tested in production

πŸ“¦ Installation

go get github.com/crazywolf132/lugo

πŸš€ Quick Start

Basic Configuration
package main

import (
    "context"
    "log"
    
    "github.com/crazywolf132/lugo"
)

// Define your configuration structure
type Config struct {
    Name     string   `lua:"name"`
    Version  string   `lua:"version"`
    Features []string `lua:"features"`
    Debug    bool     `lua:"debug"`
}

func main() {
    // Create a new Lugo instance
    cfg := lugo.New()
    defer cfg.Close()

    // Register your configuration type
    err := cfg.RegisterType(context.Background(), "config", Config{})
    if err != nil {
        log.Fatal(err)
    }

    // Load configuration from string
    err = cfg.L.DoString(`
        config = {
            name = "my-app",
            version = "1.0.0",
            features = {"feature1", "feature2"},
            debug = true
        }
    `)
    if err != nil {
        log.Fatal(err)
    }

    // Get the typed configuration
    var myConfig Config
    err = cfg.Get(context.Background(), "config", &myConfig)
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Loaded config: %+v", myConfig)
}
Advanced Usage
Registering Go Functions
package main

import (
    "context"
    "log"
    
    "github.com/crazywolf132/lugo"
)

func main() {
    cfg := lugo.New()
    defer cfg.Close()

    // Register a Go function
    err := cfg.RegisterFunction(context.Background(), "processOrder", func(ctx context.Context, orderID string, amount float64) (string, error) {
        // Process the order...
        return "processed", nil
    })
    if err != nil {
        log.Fatal(err)
    }

    // Use the function in Lua
    err = cfg.L.DoString(`
        local status, err = processOrder("123", 99.99)
        assert(status == "processed")
    `)
    if err != nil {
        log.Fatal(err)
    }
}
Using Sandbox Restrictions
package main

import (
    "context"
    "log"
    "time"
    
    "github.com/crazywolf132/lugo"
)

func main() {
    // Create a new instance with sandbox restrictions
    cfg := lugo.New(
        lugo.WithSandbox(&lugo.Sandbox{
            EnableFileIO:     false,
            EnableNetworking: false,
            MaxMemory:       50 * 1024 * 1024, // 50MB
            MaxExecutionTime: 10 * time.Second,
        }),
    )
    defer cfg.Close()

    // Try to execute restricted operations
    err := cfg.L.DoString(`
        -- This will fail due to sandbox restrictions
        local file = io.open("secret.txt", "r")
    `)
    if err != nil {
        log.Printf("Expected error: %v", err)
    }
}
Using Middleware for Metrics
package main

import (
    "context"
    "log"
    "time"
    
    "github.com/crazywolf132/lugo"
)

func main() {
    // Create a new instance with middleware
    cfg := lugo.New(
        lugo.WithMiddleware(func(next lugo.LuaFunction) lugo.LuaFunction {
            return func(ctx context.Context, L *lua.LState) ([]lua.LValue, error) {
                start := time.Now()
                results, err := next(ctx, L)
                duration := time.Since(start)
                log.Printf("Function execution took: %v", duration)
                return results, err
            }
        }),
    )
    defer cfg.Close()

    // Register and execute a function
    cfg.RegisterFunction(context.Background(), "slowOperation", func() {
        time.Sleep(100 * time.Millisecond)
    })

    cfg.L.DoString(`slowOperation()`)
}

πŸ”§ Use Cases

  • Dynamic Configuration: Load and update application configuration at runtime
  • Business Rules Engine: Implement complex business rules that can be modified without recompilation
  • Plugin System: Create a plugin system where functionality can be extended through Lua scripts
  • Game Logic: Implement game rules and behaviors in Lua while keeping core mechanics in Go
  • ETL Pipelines: Define data transformation rules in Lua for flexible data processing
  • API Configuration: Configure API routing, middleware, and handlers using Lua scripts

πŸ” Security

Lugo provides comprehensive security features through its sandbox system:

  • File system access control
  • Network access restrictions
  • Memory usage limits
  • Execution time limits
  • Function whitelist/blacklist
  • Resource usage monitoring

πŸ“ˆ Performance

  • Minimal overhead over raw Lua execution
  • Efficient type conversion between Go and Lua
  • Thread-safe for concurrent script execution
  • Memory-efficient with configurable limits
  • Fast configuration reloading

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“œ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

Built with gopher-lua

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func IsErrorCode ΒΆ added in v0.2.1

func IsErrorCode(err error, code ErrorCode) bool

IsErrorCode checks if an error is a Lugo error with a specific code

func WithContext ΒΆ added in v0.2.1

func WithContext(err error, key string, value interface{}) error

WithContext adds context information to a Lugo error

Types ΒΆ

type CLIConfig ΒΆ

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

CLIConfig represents CLI-specific configuration

func (*CLIConfig) GetPlugin ΒΆ

func (c *CLIConfig) GetPlugin(name string) (lua.LValue, bool)

GetPlugin returns a plugin by name

func (*CLIConfig) LoadPlugins ΒΆ

func (c *CLIConfig) LoadPlugins() error

LoadPlugins loads all plugins from the plugin directory

type CLIConfigOptions ΒΆ

type CLIConfigOptions struct {
	AppName       string
	PluginDir     string
	DefaultConfig string
}

CLIConfigOptions holds options for CLI configuration

type Config ΒΆ

type Config struct {
	L *lua.LState
	// contains filtered or unexported fields
}

Config represents the configuration manager

func New ΒΆ

func New(opts ...Option) *Config

New creates a new Config instance with options

func (*Config) Call ΒΆ

func (c *Config) Call(funcName string, args ...interface{}) ([]interface{}, error)

Call invokes a Lua function with automatic type conversion

func (*Config) ClearStack ΒΆ added in v0.2.1

func (c *Config) ClearStack()

ClearStack removes all values from the Lua stack.

func (*Config) Close ΒΆ

func (c *Config) Close()

Close closes the Lua state

func (*Config) ComposeFunctions ΒΆ added in v0.2.1

func (c *Config) ComposeFunctions(name string, funcs ...string) error

ComposeFunctions creates a new function that chains multiple functions together

func (*Config) DoFile ΒΆ

func (c *Config) DoFile(filename string) error

func (*Config) DoString ΒΆ

func (c *Config) DoString(script string) error

Simple helper methods for common operations

func (*Config) Eval ΒΆ

func (c *Config) Eval(expr string) (interface{}, error)

Eval evaluates a Lua expression and returns the result

func (*Config) GenerateDocs ΒΆ

func (c *Config) GenerateDocs(v interface{}, gen DocGenerator) (string, error)

func (*Config) Get ΒΆ

func (c *Config) Get(ctx context.Context, name string, target interface{}) error

Get retrieves the configuration into the provided struct with validation

func (*Config) GetGlobal ΒΆ

func (c *Config) GetGlobal(name string, target interface{}) error

GetGlobal retrieves a global variable with type conversion

func (*Config) GetRawLuaValue ΒΆ added in v0.2.1

func (c *Config) GetRawLuaValue(pos int) (lua.LValue, error)

GetRawLuaValue retrieves the raw lua.LValue at a given stack position. pos = 1 means the top of the stack. Use caution with indexing.

func (*Config) GetStackSize ΒΆ added in v0.2.1

func (c *Config) GetStackSize() int

GetStackSize returns the number of values currently on the Lua stack.

func (*Config) LoadDirectory ΒΆ

func (c *Config) LoadDirectory(dir string) error

LoadDirectory loads all .lua files from a directory

func (*Config) LoadFile ΒΆ

func (c *Config) LoadFile(ctx context.Context, filename string) error

LoadFile loads and executes a Lua file with context and hooks

func (*Config) NewCLIConfig ΒΆ

func (c *Config) NewCLIConfig(opts CLIConfigOptions) *CLIConfig

NewCLIConfig creates a new CLI configuration

func (*Config) NewEnvManager ΒΆ

func (c *Config) NewEnvManager(configDir string) *EnvManager

NewEnvManager creates a new environment manager

func (*Config) NewPluginManager ΒΆ

func (c *Config) NewPluginManager(pcfg PluginConfig) *PluginManager

NewPluginManager creates a new plugin manager

func (*Config) NewWatcher ΒΆ

func (c *Config) NewWatcher(wcfg WatcherConfig) (*ConfigWatcher, error)

NewWatcher creates a new configuration watcher

func (*Config) PeekValue ΒΆ added in v0.2.1

func (c *Config) PeekValue(pos int) (interface{}, error)

PeekValue returns the value at the given stack position (1-based index from the top) without removing it. pos = 1 means the top of the stack, pos = 2 means one below the top, and so on. Returns an error if pos is out of range.

func (*Config) PopValue ΒΆ added in v0.2.1

func (c *Config) PopValue() (interface{}, error)

PopValue pops a value from the top of the Lua stack and converts it to a Go value. Returns an error if the conversion fails.

func (*Config) ProcessTemplate ΒΆ

func (c *Config) ProcessTemplate(filename string, tcfg TemplateConfig) error

ProcessTemplate processes a Lua configuration file as a template

func (*Config) PushLuaValue ΒΆ added in v0.2.1

func (c *Config) PushLuaValue(v lua.LValue)

PushLuaValue pushes a raw lua.LValue onto the stack without conversion.

func (*Config) PushValue ΒΆ added in v0.2.1

func (c *Config) PushValue(v interface{}) error

PushValue pushes a Go value onto the Lua stack, converting it to a Lua value.

func (*Config) RegisterConstants ΒΆ

func (c *Config) RegisterConstants(constants map[string]interface{}) error

RegisterConstants registers multiple constants at once

func (*Config) RegisterFunction ΒΆ

func (c *Config) RegisterFunction(ctx context.Context, name string, fn interface{}) error

RegisterFunction registers a Go function in the Lua environment with middlewares

func (*Config) RegisterFunctionTable ΒΆ added in v0.2.1

func (c *Config) RegisterFunctionTable(ctx context.Context, name string, funcs map[string]interface{}) error

RegisterFunctionTable registers multiple functions in a table with context

func (*Config) RegisterHook ΒΆ

func (c *Config) RegisterHook(hookType HookType, hook Hook)

RegisterHook registers a hook for a specific point

func (*Config) RegisterLuaFunction ΒΆ added in v0.2.1

func (c *Config) RegisterLuaFunction(name string, fn func(*lua.LState) int) error

RegisterLuaFunction registers a basic Lua function

func (*Config) RegisterLuaFunctionString ΒΆ added in v0.2.1

func (c *Config) RegisterLuaFunctionString(name string, luaCode string) error

RegisterLuaFunctionString registers a Lua function from a string

func (*Config) RegisterLuaFunctionWithOptions ΒΆ added in v0.2.1

func (c *Config) RegisterLuaFunctionWithOptions(name string, fn func(*lua.LState) int, opts FunctionOptions) error

RegisterLuaFunctionWithOptions registers a Lua function with advanced options

func (*Config) RegisterType ΒΆ

func (c *Config) RegisterType(ctx context.Context, name string, typeStruct interface{}, defaultValue ...interface{}) error

RegisterType registers a Go struct as a Lua type with optional default values

func (*Config) SetGlobal ΒΆ

func (c *Config) SetGlobal(name string, value interface{}) error

SetGlobal sets a global variable with type conversion

type ConfigWatcher ΒΆ

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

ConfigWatcher watches for configuration changes and reloads automatically

func (*ConfigWatcher) AddPath ΒΆ

func (w *ConfigWatcher) AddPath(path string) error

AddPath adds a path to watch

func (*ConfigWatcher) Close ΒΆ

func (w *ConfigWatcher) Close() error

Close stops watching for changes

func (*ConfigWatcher) RemovePath ΒΆ

func (w *ConfigWatcher) RemovePath(path string) error

RemovePath removes a path from watching

type DocGenerator ΒΆ

type DocGenerator struct {
	Format           string
	TypeDescriptions map[string]string
	IncludeExamples  bool
}

type EnvManager ΒΆ

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

EnvManager manages different configuration environments

func (*EnvManager) ActivateEnvironment ΒΆ

func (em *EnvManager) ActivateEnvironment(name string) error

ActivateEnvironment activates a specific environment

func (*EnvManager) GetActiveEnvironment ΒΆ

func (em *EnvManager) GetActiveEnvironment() string

GetActiveEnvironment returns the currently active environment

func (*EnvManager) RegisterEnvironment ΒΆ

func (em *EnvManager) RegisterEnvironment(env *Environment) error

RegisterEnvironment registers a new environment

type Environment ΒΆ

type Environment struct {
	// Name of the environment
	Name string
	// Base configuration that applies to all environments
	BaseConfig string
	// Environment-specific configuration
	EnvConfig string
	// Environment variables prefix for this environment
	EnvPrefix string
	// Additional configuration paths
	IncludePaths []string
}

Environment represents a configuration environment (e.g., dev, staging, prod)

type Error ΒΆ

type Error struct {
	Code     ErrorCode
	Message  string
	Cause    error
	Context  map[string]interface{} // Additional context for debugging
	Location string                 // File/line information
}

func NewError ΒΆ added in v0.2.1

func NewError(code ErrorCode, message string) *Error

NewError creates a new Lugo error with the given code and message

func WrapError ΒΆ added in v0.2.1

func WrapError(code ErrorCode, message string, cause error) *Error

WrapError wraps an existing error with Lugo error context

func (*Error) Error ΒΆ

func (e *Error) Error() string

func (*Error) Unwrap ΒΆ added in v0.2.1

func (e *Error) Unwrap() error

type ErrorCode ΒΆ

type ErrorCode int

Error handling

const (
	ErrInvalidType ErrorCode = iota
	ErrNotFound
	ErrValidation
	ErrSandbox
	ErrExecution
	ErrTimeout
	ErrCanceled
	ErrIO
	ErrParse
	ErrConversion
)

type EventHandler ΒΆ

type EventHandler func(ctx context.Context, data interface{}) error

EventHandler represents a function that handles plugin events

type FunctionMetadata ΒΆ added in v0.2.1

type FunctionMetadata struct {
	Description string           // Function description
	Author      string           // Function author
	Version     string           // Function version
	Deprecated  bool             // Whether the function is deprecated
	Tags        []string         // Function tags for categorization
	Params      []ParamMetadata  // Parameter descriptions
	Returns     []ReturnMetadata // Return value descriptions
	Examples    []string         // Usage examples
	Middleware  []string         // Applied middleware names
}

FunctionMetadata contains information about a registered function

type FunctionOptions ΒΆ added in v0.2.1

type FunctionOptions struct {
	Metadata   *FunctionMetadata
	Namespace  string   // Function namespace (e.g., "http.client")
	Aliases    []string // Alternative names for the function
	Middleware []string // Middleware to apply
	BeforeCall func(*lua.LState) error
	AfterCall  func(*lua.LState, error)
}

FunctionOptions configures a function registration

type Generator ΒΆ

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

Generator provides a fluent API for generating Lua code

func NewGenerator ΒΆ

func NewGenerator() *Generator

NewGenerator creates a new Lua code generator

func (*Generator) Array ΒΆ

func (g *Generator) Array(values ...interface{}) *Generator

Array adds an array to the current table

func (*Generator) Comment ΒΆ

func (g *Generator) Comment(text string) *Generator

Comment adds a comment

func (*Generator) EndFunction ΒΆ

func (g *Generator) EndFunction() *Generator

EndFunction closes a function declaration

func (*Generator) EndTable ΒΆ

func (g *Generator) EndTable() *Generator

EndTable closes a table declaration

func (*Generator) Field ΒΆ

func (g *Generator) Field(name string, value interface{}) *Generator

Field adds a field to the current table

func (*Generator) Function ΒΆ

func (g *Generator) Function(name string, params ...string) *Generator

Function adds a function declaration

func (*Generator) Raw ΒΆ

func (g *Generator) Raw(code string) *Generator

Raw adds raw Lua code

func (*Generator) Reset ΒΆ

func (g *Generator) Reset()

Reset clears the generator buffer

func (*Generator) String ΒΆ

func (g *Generator) String() string

String returns the generated Lua code as a string

func (*Generator) Table ΒΆ

func (g *Generator) Table(name string) *Generator

Table starts a new table declaration

type Hook ΒΆ

type Hook func(ctx context.Context, event HookEvent) error

Hook represents a function that can be called at various points

type HookEvent ΒΆ

type HookEvent struct {
	Type    HookType
	Name    string
	Args    []interface{}
	Result  interface{}
	Error   error
	Elapsed time.Duration
}

HookEvent contains information about the hook execution

type HookType ΒΆ

type HookType int

HookType represents different hook points

const (
	BeforeLoad HookType = iota
	AfterLoad
	BeforeExec
	AfterExec
)

type LuaError ΒΆ added in v0.2.1

type LuaError struct {
	BaseError *Error // Renamed from Error to BaseError to avoid naming conflict
	Stack     []LuaStackTrace
}

LuaError represents a Lua-specific error with stack trace

func NewLuaError ΒΆ added in v0.2.1

func NewLuaError(L *lua.LState, code ErrorCode, message string, cause error) *LuaError

NewLuaError creates a new LuaError with stack trace from the current Lua state

func WrapLuaError ΒΆ added in v0.2.1

func WrapLuaError(L *lua.LState, err error) *LuaError

WrapLuaError wraps a Lua runtime error with stack trace

func (*LuaError) Code ΒΆ added in v0.2.1

func (e *LuaError) Code() ErrorCode

Code returns the error code

func (*LuaError) Error ΒΆ added in v0.2.1

func (e *LuaError) Error() string

Error implements the error interface

func (*LuaError) Unwrap ΒΆ added in v0.2.1

func (e *LuaError) Unwrap() error

Unwrap implements the error unwrapping interface

type LuaFunction ΒΆ

type LuaFunction func(ctx context.Context, L *lua.LState) ([]lua.LValue, error)

LuaFunction represents a function that can be called from Lua

type LuaStackTrace ΒΆ added in v0.2.1

type LuaStackTrace struct {
	Source   string // Source file or chunk name
	Line     int    // Line number
	Function string // Function name
}

LuaStackTrace represents a Lua stack frame

type Middleware ΒΆ

type Middleware func(next LuaFunction) LuaFunction

Middleware represents a function that can modify behavior

type Option ΒΆ

type Option func(*Config)

Option represents a configuration option

func WithLogger ΒΆ

func WithLogger(logger *zap.Logger) Option

WithLogger sets the logger

func WithMiddleware ΒΆ

func WithMiddleware(middleware Middleware) Option

WithMiddleware adds middleware

func WithSandbox ΒΆ

func WithSandbox(sandbox *Sandbox) Option

WithSandbox sets sandbox options

type ParamMetadata ΒΆ added in v0.2.1

type ParamMetadata struct {
	Name        string
	Type        string
	Description string
	Optional    bool
	Default     interface{}
}

ParamMetadata describes a function parameter

type Plugin ΒΆ

type Plugin struct {
	Name        string
	Version     string
	Description string
	Path        string
	Exports     map[string]interface{}
	State       *lua.LState
}

Plugin represents a loaded plugin

type PluginAPI ΒΆ

type PluginAPI interface {
	// RegisterFunction registers a function that can be called from Lua
	RegisterFunction(name string, fn interface{}) error
	// RegisterHook registers a hook that will be called at specific points
	RegisterHook(hookType HookType, hook Hook) error
	// GetConfig returns the current configuration
	GetConfig() *Config
	// EmitEvent emits an event that other plugins can listen to
	EmitEvent(name string, data interface{}) error
}

PluginAPI represents the interface that plugins can use to interact with the host application

type PluginConfig ΒΆ

type PluginConfig struct {
	// Directory containing plugins
	PluginDir string
	// Plugin-specific sandbox settings
	Sandbox *Sandbox
	// Custom API implementation
	API PluginAPI
	// Allowed plugin types (e.g., "lua", "so")
	AllowedTypes []string
	// Plugin metadata requirements
	RequiredMetadata []string
}

PluginConfig holds configuration for plugin loading

type PluginManager ΒΆ

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

PluginManager handles plugin loading and lifecycle

func (*PluginManager) CallPluginFunction ΒΆ

func (pm *PluginManager) CallPluginFunction(ctx context.Context, pluginName, funcName string, args ...interface{}) (interface{}, error)

CallPluginFunction calls an exported plugin function

func (*PluginManager) EmitEvent ΒΆ

func (pm *PluginManager) EmitEvent(ctx context.Context, event string, data interface{}) error

EmitEvent emits an event to all registered handlers

func (*PluginManager) GetPlugin ΒΆ

func (pm *PluginManager) GetPlugin(name string) (*Plugin, bool)

GetPlugin returns a loaded plugin by name

func (*PluginManager) LoadPlugins ΒΆ

func (pm *PluginManager) LoadPlugins(ctx context.Context, dir string) error

LoadPlugins loads all plugins from the configured directory

func (*PluginManager) RegisterEventHandler ΒΆ

func (pm *PluginManager) RegisterEventHandler(event string, handler EventHandler)

RegisterEventHandler registers a handler for plugin events

type ReturnMetadata ΒΆ added in v0.2.1

type ReturnMetadata struct {
	Name        string
	Type        string
	Description string
}

ReturnMetadata describes a function return value

type Sandbox ΒΆ

type Sandbox struct {
	EnableFileIO     bool
	EnableNetworking bool
	EnableSyscalls   bool
	MaxMemory        uint64 // in bytes
	MaxExecutionTime time.Duration
	AllowedPaths     []string
	BlockedPaths     []string
}

Sandbox provides security restrictions

type SchemaValidator ΒΆ

type SchemaValidator struct {
	// Required fields
	Required []string
	// Pattern matching for string fields
	Patterns map[string]*regexp.Regexp
	// Range validation for numeric fields
	Ranges map[string]struct {
		Min, Max float64
	}
	// Custom validation functions
	CustomValidators map[string]func(interface{}) error
	// Nested validators for complex types
	Nested map[string]*SchemaValidator
}

SchemaValidator defines validation rules for configuration

func NewSchemaValidator ΒΆ

func NewSchemaValidator() *SchemaValidator

NewSchemaValidator creates a new schema validator

func (*SchemaValidator) AddCustomValidator ΒΆ

func (sv *SchemaValidator) AddCustomValidator(field string, validator func(interface{}) error)

AddCustomValidator adds a custom validation function for a field

func (*SchemaValidator) AddNestedValidator ΒΆ

func (sv *SchemaValidator) AddNestedValidator(field string, validator *SchemaValidator)

AddNestedValidator adds a validator for nested structures

func (*SchemaValidator) AddPattern ΒΆ

func (sv *SchemaValidator) AddPattern(field, pattern string) error

AddPattern adds a regex pattern validation for a field

func (*SchemaValidator) AddRange ΒΆ

func (sv *SchemaValidator) AddRange(field string, min, max float64)

AddRange adds numeric range validation for a field

func (*SchemaValidator) Validate ΒΆ

func (sv *SchemaValidator) Validate(cfg interface{}) error

Validate validates a configuration against the schema

type TemplateConfig ΒΆ

type TemplateConfig struct {
	Variables  map[string]interface{}
	Functions  template.FuncMap
	LeftDelim  string
	RightDelim string
}

TemplateConfig holds configuration for template processing

type TypeConverter ΒΆ added in v0.2.1

type TypeConverter struct{}

TypeConverter provides methods for safe type conversion

func (*TypeConverter) ToBool ΒΆ added in v0.2.1

func (tc *TypeConverter) ToBool(v interface{}) (bool, error)

ToBool converts any supported value to bool

func (*TypeConverter) ToFloat ΒΆ added in v0.2.1

func (tc *TypeConverter) ToFloat(v interface{}) (float64, error)

ToFloat converts any supported value to float64

func (*TypeConverter) ToInt ΒΆ added in v0.2.1

func (tc *TypeConverter) ToInt(v interface{}) (int64, error)

ToInt converts any supported value to int64

func (*TypeConverter) ToString ΒΆ added in v0.2.1

func (tc *TypeConverter) ToString(v interface{}) (string, error)

ToString converts any supported value to string

type WatcherConfig ΒΆ

type WatcherConfig struct {
	// Paths to watch for changes
	Paths []string
	// How often to poll for changes (for non-inotify systems)
	PollInterval time.Duration
	// Debounce period to avoid multiple reloads
	DebounceInterval time.Duration
	// Callback function when configuration is reloaded
	OnReload func(error)
}

WatcherConfig contains settings for the configuration watcher

Directories ΒΆ

Path Synopsis
_examples
advanced command
basic command
middleware command
templates command
validation command
watcher command

Jump to

Keyboard shortcuts

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