Documentation
¶
Overview ¶
Cli is the CLI surface layer for the Core command tree. It reads commands from Core's registry and wires them to terminal I/O.
Run the CLI:
c := core.New(core.Options{{Key: "name", Value: "myapp"}})
c.Command("deploy", handler)
c.Cli().Run()
The Cli resolves os.Args to a command path, parses flags, and calls the command's action with parsed options.
Command is a DTO representing an executable operation. Commands don't know if they're root, child, or nested — the tree structure comes from composition via path-based registration.
Register a command:
c.Command("deploy", func(opts core.Options) core.Result {
return core.Result{"deployed", true}
})
Register a nested command:
c.Command("deploy/to/homelab", handler)
Description is an i18n key — derived from path if omitted:
"deploy" → "cmd.deploy.description" "deploy/to/homelab" → "cmd.deploy.to.homelab.description"
Data is the embedded/stored content system for core packages. Packages mount their embedded content here and other packages read from it by path.
Mount a package's assets:
c.Data().New(core.Options{
{Key: "name", Value: "brain"},
{Key: "source", Value: brainFS},
{Key: "path", Value: "prompts"},
})
Read from any mounted path:
content := c.Data().ReadString("brain/coding.md")
entries := c.Data().List("agent/flow")
Extract a template directory:
c.Data().Extract("agent/workspace/default", "/tmp/ws", data)
Drive is the resource handle registry for transport connections. Packages register their transport handles (API, MCP, SSH, VPN) and other packages access them by name.
Register a transport:
c.Drive().New(core.Options{
{Key: "name", Value: "api"},
{Key: "transport", Value: "https://api.lthn.ai"},
})
c.Drive().New(core.Options{
{Key: "name", Value: "ssh"},
{Key: "transport", Value: "ssh://claude@10.69.69.165"},
})
c.Drive().New(core.Options{
{Key: "name", Value: "mcp"},
{Key: "transport", Value: "mcp://mcp.lthn.sh"},
})
Retrieve a handle:
api := c.Drive().Get("api")
Embedded assets for the Core framework.
Embed provides scoped filesystem access for go:embed and any fs.FS. Also includes build-time asset packing (AST scanner + compressor) and template-based directory extraction.
Usage (mount):
sub, _ := core.Mount(myFS, "lib/persona")
content, _ := sub.ReadString("secops/developer.md")
Usage (extract):
core.Extract(fsys, "/tmp/workspace", data)
Usage (pack):
refs, _ := core.ScanAssets([]string{"main.go"})
source, _ := core.GeneratePack(refs)
Sandboxed local filesystem I/O for the Core framework.
Structured logging for the Core framework.
core.SetLevel(core.LevelDebug)
core.Info("server started", "port", 8080)
core.Error("failed to connect", "err", err)
Core primitives: Option, Options, Result.
Option is a single key-value pair. Options is a collection. Any function that returns Result can accept Options.
Create options:
opts := core.Options{
{Key: "name", Value: "brain"},
{Key: "path", Value: "prompts"},
}
Read options:
name := opts.String("name")
port := opts.Int("port")
ok := opts.Has("debug")
Use with subsystems:
c.Drive().New(core.Options{
{Key: "name", Value: "brain"},
{Key: "source", Value: brainFS},
{Key: "path", Value: "prompts"},
})
Use with New:
c := core.New(core.Options{
{Key: "name", Value: "myapp"},
})
Index ¶
- Variables
- func AddAsset(group, name, data string)
- func AllOperations(err error) iter.Seq[string]
- func ArgBool(index int, args ...any) bool
- func ArgInt(index int, args ...any) int
- func ArgString(index int, args ...any) string
- func As(err error, target any) bool
- func Concat(parts ...string) string
- func ConfigGet[T any](e *Config, key string) T
- func Contains(s, substr string) bool
- func Debug(msg string, keyvals ...any)
- func E(op, msg string, err error) error
- func Error(msg string, keyvals ...any)
- func ErrorCode(err error) string
- func ErrorJoin(errs ...error) error
- func ErrorMessage(err error) string
- func FilterArgs(args []string) []string
- func FormatStackTrace(err error) string
- func HasPrefix(s, prefix string) bool
- func HasSuffix(s, suffix string) bool
- func Info(msg string, keyvals ...any)
- func Is(err, target error) bool
- func IsFlag(arg string) bool
- func Join(sep string, parts ...string) string
- func JoinPath(segments ...string) string
- func Lower(s string) string
- func NewBuilder() *strings.Builder
- func NewCode(code, msg string) error
- func NewError(text string) error
- func NewReader(s string) *strings.Reader
- func Operation(err error) string
- func ParseFlag(arg string) (key, value string, valid bool)
- func Print(w io.Writer, format string, args ...any)
- func Replace(s, old, new string) string
- func Root(err error) error
- func RuneCount(s string) int
- func Security(msg string, keyvals ...any)
- func SetDefault(l *Log)
- func SetLevel(level Level)
- func SetRedactKeys(keys ...string)
- func Split(s, sep string) []string
- func SplitN(s, sep string, n int) []string
- func Sprint(args ...any) string
- func Sprintf(format string, args ...any) string
- func StackTrace(err error) []string
- func Trim(s string) string
- func TrimPrefix(s, prefix string) string
- func TrimSuffix(s, suffix string) string
- func Upper(s string) string
- func Username() string
- func Warn(msg string, keyvals ...any)
- func Wrap(err error, op, msg string) error
- func WrapCode(err error, code, op, msg string) error
- type ActionServiceShutdown
- type ActionServiceStartup
- type ActionTaskCompleted
- type ActionTaskProgress
- type ActionTaskStarted
- type App
- type Array
- func (s *Array[T]) Add(values ...T)
- func (s *Array[T]) AddUnique(values ...T)
- func (s *Array[T]) AsSlice() []T
- func (s *Array[T]) Clear()
- func (s *Array[T]) Contains(val T) bool
- func (s *Array[T]) Deduplicate()
- func (s *Array[T]) Each(fn func(T))
- func (s *Array[T]) Filter(fn func(T) bool) Result
- func (s *Array[T]) Len() int
- func (s *Array[T]) Remove(val T)
- type AssetGroup
- type AssetRef
- type Cli
- type Command
- type CommandAction
- type CommandLifecycle
- type Config
- func (e *Config) Bool(key string) bool
- func (e *Config) Disable(feature string)
- func (e *Config) Enable(feature string)
- func (e *Config) Enabled(feature string) bool
- func (e *Config) EnabledFeatures() []string
- func (e *Config) Get(key string) Result
- func (e *Config) Int(key string) int
- func (e *Config) Set(key string, val any)
- func (e *Config) String(key string) string
- type ConfigOptions
- type ConfigVar
- type Core
- func (c *Core) ACTION(msg Message) Result
- func (c *Core) Action(msg Message) Result
- func (c *Core) App() *App
- func (c *Core) Cli() *Cli
- func (c *Core) Command(path string, command ...Command) Result
- func (c *Core) Commands() []string
- func (c *Core) Config() *Config
- func (c *Core) Context() context.Context
- func (c *Core) Core() *Core
- func (c *Core) Data() *Data
- func (c *Core) Drive() *Drive
- func (c *Core) Embed() Result
- func (c *Core) Error() *ErrorPanic
- func (c *Core) Fs() *Fs
- func (c *Core) I18n() *I18n
- func (c *Core) IPC() *Ipc
- func (c *Core) Lock(name string) *Lock
- func (c *Core) LockApply(name ...string)
- func (c *Core) LockEnable(name ...string)
- func (c *Core) Log() *ErrorLog
- func (c *Core) LogError(err error, op, msg string) Result
- func (c *Core) LogWarn(err error, op, msg string) Result
- func (c *Core) Must(err error, op, msg string)
- func (c *Core) Options() *Options
- func (c *Core) PERFORM(t Task) Result
- func (c *Core) Perform(t Task) Result
- func (c *Core) PerformAsync(t Task) Result
- func (c *Core) Progress(taskID string, progress float64, message string, t Task)
- func (c *Core) QUERY(q Query) Result
- func (c *Core) QUERYALL(q Query) Result
- func (c *Core) Query(q Query) Result
- func (c *Core) QueryAll(q Query) Result
- func (c *Core) RegisterAction(handler func(*Core, Message) Result)
- func (c *Core) RegisterActions(handlers ...func(*Core, Message) Result)
- func (c *Core) RegisterQuery(handler QueryHandler)
- func (c *Core) RegisterTask(handler TaskHandler)
- func (c *Core) Service(name string, service ...Service) Result
- func (c *Core) ServiceShutdown(ctx context.Context) Result
- func (c *Core) ServiceStartup(ctx context.Context, options any) Result
- func (c *Core) Services() []string
- func (c *Core) Startables() Result
- func (c *Core) Stoppables() Result
- type CrashReport
- type CrashSystem
- type Data
- func (d *Data) Extract(path, targetDir string, templateData any) Result
- func (d *Data) Get(name string) Result
- func (d *Data) List(path string) Result
- func (d *Data) ListNames(path string) Result
- func (d *Data) Mounts() []string
- func (d *Data) New(opts Options) Result
- func (d *Data) ReadFile(path string) Result
- func (d *Data) ReadString(path string) Result
- type Drive
- type DriveHandle
- type Embed
- func (s *Embed) BaseDirectory() string
- func (s *Embed) EmbedFS() embed.FS
- func (s *Embed) FS() fs.FS
- func (s *Embed) Open(name string) Result
- func (s *Embed) ReadDir(name string) Result
- func (s *Embed) ReadFile(name string) Result
- func (s *Embed) ReadString(name string) Result
- func (s *Embed) Sub(subDir string) Result
- type Err
- type ErrorLog
- type ErrorPanic
- type ErrorSink
- type ExtractOptions
- type Fs
- func (m *Fs) Append(p string) Result
- func (m *Fs) Create(p string) Result
- func (m *Fs) Delete(p string) Result
- func (m *Fs) DeleteAll(p string) Result
- func (m *Fs) EnsureDir(p string) Result
- func (m *Fs) Exists(p string) bool
- func (m *Fs) IsDir(p string) bool
- func (m *Fs) IsFile(p string) bool
- func (m *Fs) List(p string) Result
- func (m *Fs) Open(p string) Result
- func (m *Fs) Read(p string) Result
- func (m *Fs) ReadStream(path string) Result
- func (m *Fs) Rename(oldPath, newPath string) Result
- func (m *Fs) Stat(p string) Result
- func (m *Fs) Write(p, content string) Result
- func (m *Fs) WriteMode(p, content string, mode os.FileMode) Result
- func (m *Fs) WriteStream(path string) Result
- type I18n
- func (i *I18n) AddLocales(mounts ...*Embed)
- func (i *I18n) AvailableLanguages() []string
- func (i *I18n) Language() string
- func (i *I18n) Locales() Result
- func (i *I18n) SetLanguage(lang string) Result
- func (i *I18n) SetTranslator(t Translator)
- func (i *I18n) Translate(messageID string, args ...any) Result
- func (i *I18n) Translator() Result
- type Ipc
- type Level
- type LocaleProvider
- type Lock
- type Log
- func (l *Log) Debug(msg string, keyvals ...any)
- func (l *Log) Error(msg string, keyvals ...any)
- func (l *Log) Info(msg string, keyvals ...any)
- func (l *Log) Level() Level
- func (l *Log) Security(msg string, keyvals ...any)
- func (l *Log) SetLevel(level Level)
- func (l *Log) SetOutput(w goio.Writer)
- func (l *Log) SetRedactKeys(keys ...string)
- func (l *Log) Warn(msg string, keyvals ...any)
- type LogErr
- type LogOptions
- type LogPanic
- type Message
- type Option
- type Options
- type Query
- type QueryHandler
- type Result
- func Arg(index int, args ...any) Result
- func Extract(fsys fs.FS, targetDir string, data any, opts ...ExtractOptions) Result
- func Find(filename, name string) Result
- func GeneratePack(pkg ScannedPackage) Result
- func GetAsset(group, name string) Result
- func GetAssetBytes(group, name string) Result
- func Mount(fsys fs.FS, basedir string) Result
- func MountEmbed(efs embed.FS, basedir string) Result
- func NewRuntime(app any) Result
- func NewWithFactories(app any, factories map[string]ServiceFactory) Result
- func ScanAssets(filenames []string) Result
- type RotationLogOptions
- type Runtime
- type ScannedPackage
- type Service
- type ServiceFactory
- type ServiceRuntime
- type Startable
- type Stoppable
- type Task
- type TaskHandler
- type TaskState
- type TaskWithIdentifier
- type Translator
Constants ¶
This section is empty.
Variables ¶
var RotationWriterFactory func(RotationLogOptions) goio.WriteCloser
RotationWriterFactory creates a rotating writer from options. Set this to enable log rotation (provided by core/go-io integration).
Functions ¶
func AddAsset ¶
func AddAsset(group, name, data string)
AddAsset registers a packed asset at runtime (called from generated init()).
func AllOperations ¶
AllOperations returns an iterator over all operational contexts in the error chain. It traverses the error tree using errors.Unwrap.
func As ¶
As finds the first error in err's tree that matches target. Wrapper around errors.As for convenience.
func Concat ¶
Concat joins variadic string parts into one string. Hook point for validation, sanitisation, and security checks.
core.Concat("cmd.", "deploy.to.homelab", ".description")
core.Concat("https://", host, "/api/v1")
func Contains ¶
Contains returns true if s contains substr.
core.Contains("hello world", "world") // true
func E ¶
E creates a new Err with operation context. The underlying error can be nil for creating errors without a cause.
Example:
return log.E("user.Save", "failed to save user", err)
return log.E("api.Call", "rate limited", nil) // No underlying cause
func ErrorCode ¶
ErrorCode extracts the error code from an error. Returns empty string if the error is not an *Err or has no code.
func ErrorMessage ¶
Message extracts the message from an error. Returns the error's Error() string if not an *Err.
func FilterArgs ¶
FilterArgs removes empty strings and Go test runner flags from an argument list.
clean := core.FilterArgs(os.Args[1:])
func FormatStackTrace ¶
FormatStackTrace returns a pretty-printed logical stack trace.
func HasPrefix ¶
HasPrefix returns true if s starts with prefix.
core.HasPrefix("--verbose", "--") // true
func HasSuffix ¶
HasSuffix returns true if s ends with suffix.
core.HasSuffix("test.go", ".go") // true
func Is ¶
Is reports whether any error in err's tree matches target. Wrapper around errors.Is for convenience.
func IsFlag ¶
IsFlag returns true if the argument starts with a dash.
core.IsFlag("--verbose") // true
core.IsFlag("-v") // true
core.IsFlag("deploy") // false
func Join ¶
Join joins parts with a separator, building via Concat.
core.Join("/", "deploy", "to", "homelab") // "deploy/to/homelab"
core.Join(".", "cmd", "deploy", "description") // "cmd.deploy.description"
func JoinPath ¶
JoinPath joins string segments into a path with "/" separator.
core.JoinPath("deploy", "to", "homelab") // → "deploy/to/homelab"
func NewBuilder ¶
NewBuilder returns a new strings.Builder.
b := core.NewBuilder()
b.WriteString("hello")
b.String() // "hello"
func NewCode ¶
NewCode creates an error with just code and message (no underlying error). Useful for creating sentinel errors with codes.
Example:
var ErrNotFound = log.NewCode("NOT_FOUND", "resource not found")
func NewError ¶
NewError creates a simple error with the given text. Wrapper around errors.New for convenience.
func NewReader ¶
NewReader returns a strings.NewReader for the given string.
r := core.NewReader("hello world")
func Operation ¶
Operation extracts the operation name from an error. Returns empty string if the error is not an *Err.
func ParseFlag ¶
ParseFlag parses a single flag argument into key, value, and validity. Single dash (-) requires exactly 1 character (letter, emoji, unicode). Double dash (--) requires 2+ characters.
"-v" → "v", "", true "-🔥" → "🔥", "", true "--verbose" → "verbose", "", true "--port=8080" → "port", "8080", true "-verbose" → "", "", false (single dash, 2+ chars) "--v" → "", "", false (double dash, 1 char) "hello" → "", "", false (not a flag)
func Print ¶
Print writes a formatted line to a writer, defaulting to os.Stdout.
core.Print(nil, "hello %s", "world") // → stdout core.Print(w, "port: %d", 8080) // → w
func Replace ¶
Replace replaces all occurrences of old with new in s.
core.Replace("deploy/to/homelab", "/", ".") // "deploy.to.homelab"
func Root ¶
Root returns the root cause of an error chain. Unwraps until no more wrapped errors are found.
func RuneCount ¶
RuneCount returns the number of runes (unicode characters) in s.
core.RuneCount("hello") // 5
core.RuneCount("🔥") // 1
func SetRedactKeys ¶
func SetRedactKeys(keys ...string)
SetRedactKeys sets the default logger's redaction keys.
func SplitN ¶
SplitN splits s by separator into at most n parts.
core.SplitN("key=value=extra", "=", 2) // ["key", "value=extra"]
func Sprint ¶
Sprint converts any value to its string representation.
core.Sprint(42) // "42" core.Sprint(err) // "connection refused"
func Sprintf ¶
Sprintf formats a string with the given arguments.
core.Sprintf("%v=%q", "key", "value") // `key="value"`
func StackTrace ¶
StackTrace returns the logical stack trace (chain of operations) from an error. It returns an empty slice if no operational context is found.
func Username ¶
func Username() string
Username returns the current system username. It uses os/user for reliability and falls back to environment variables.
func Wrap ¶
Wrap wraps an error with operation context. Returns nil if err is nil, to support conditional wrapping. Preserves error Code if the wrapped error is an *Err.
Example:
return log.Wrap(err, "db.Query", "database query failed")
Types ¶
type ActionServiceShutdown ¶
type ActionServiceShutdown struct{}
type ActionServiceStartup ¶
type ActionServiceStartup struct{}
type ActionTaskCompleted ¶
type ActionTaskProgress ¶
type ActionTaskStarted ¶
type App ¶
type App struct {
// Name is the human-readable application name (e.g., "Core CLI").
Name string
// Version is the application version string (e.g., "1.2.3").
Version string
// Description is a short description of the application.
Description string
// Filename is the executable filename (e.g., "core").
Filename string
// Path is the absolute path to the executable.
Path string
// Runtime is the GUI runtime (e.g., Wails App).
// Nil for CLI-only applications.
Runtime any
}
App holds the application identity and optional GUI runtime.
type Array ¶
type Array[T comparable] struct { // contains filtered or unexported fields }
Array is a typed slice with common operations.
func (*Array[T]) AddUnique ¶
func (s *Array[T]) AddUnique(values ...T)
AddUnique appends values only if not already present.
func (*Array[T]) AsSlice ¶
func (s *Array[T]) AsSlice() []T
AsSlice returns a copy of the underlying slice.
func (*Array[T]) Deduplicate ¶
func (s *Array[T]) Deduplicate()
Deduplicate removes duplicate values, preserving order.
type AssetGroup ¶
type AssetGroup struct {
// contains filtered or unexported fields
}
AssetGroup holds a named collection of packed assets.
type Cli ¶
type Cli struct {
// contains filtered or unexported fields
}
Cli is the CLI surface for the Core command tree.
func (*Cli) Print ¶
Print writes to the CLI output (defaults to os.Stdout).
c.Cli().Print("hello %s", "world")
func (*Cli) PrintHelp ¶
func (cl *Cli) PrintHelp()
PrintHelp prints available commands.
c.Cli().PrintHelp()
func (*Cli) Run ¶
Run resolves os.Args to a command path and executes it.
c.Cli().Run()
c.Cli().Run("deploy", "to", "homelab")
type Command ¶
type Command struct {
Name string
Description string // i18n key — derived from path if empty
Path string // "deploy/to/homelab"
Action CommandAction // business logic
Lifecycle CommandLifecycle // optional — provided by go-process
Flags Options // declared flags
Hidden bool
// contains filtered or unexported fields
}
Command is the DTO for an executable operation.
func (*Command) I18nKey ¶
I18nKey returns the i18n key for this command's description.
cmd with path "deploy/to/homelab" → "cmd.deploy.to.homelab.description"
func (*Command) Run ¶
Run executes the command's action with the given options.
result := cmd.Run(core.Options{{Key: "target", Value: "homelab"}})
type CommandAction ¶
CommandAction is the function signature for command handlers.
func(opts core.Options) core.Result
type CommandLifecycle ¶
type CommandLifecycle interface {
Start(Options) Result
Stop() Result
Restart() Result
Reload() Result
Signal(string) Result
}
CommandLifecycle is implemented by commands that support managed lifecycle. Basic commands only need an action. Daemon commands implement Start/Stop/Signal via go-process.
type Config ¶
type Config struct {
*ConfigOptions
// contains filtered or unexported fields
}
Config holds configuration settings and feature flags.
func (*Config) EnabledFeatures ¶
type ConfigOptions ¶
ConfigOptions holds configuration data.
type ConfigVar ¶
type ConfigVar[T any] struct { // contains filtered or unexported fields }
ConfigVar is a variable that can be set, unset, and queried for its state.
func NewConfigVar ¶
type Core ¶
type Core struct {
// contains filtered or unexported fields
}
Core is the central application object that manages services, assets, and communication.
func New ¶
New creates a Core instance.
c := core.New(core.Options{
{Key: "name", Value: "myapp"},
})
func (*Core) Command ¶
Command gets or registers a command by path.
c.Command("deploy", Command{Action: handler})
r := c.Command("deploy")
func (*Core) Error ¶
func (c *Core) Error() *ErrorPanic
func (*Core) LockEnable ¶
LockEnable marks that the service lock should be applied after initialisation.
func (*Core) PerformAsync ¶
PerformAsync dispatches a task in a background goroutine.
func (*Core) RegisterActions ¶
func (*Core) RegisterQuery ¶
func (c *Core) RegisterQuery(handler QueryHandler)
func (*Core) RegisterTask ¶
func (c *Core) RegisterTask(handler TaskHandler)
func (*Core) Service ¶
Service gets or registers a service by name.
c.Service("auth", core.Service{OnStart: startFn})
r := c.Service("auth")
func (*Core) ServiceShutdown ¶
ServiceShutdown drains background tasks, then stops all registered services.
func (*Core) ServiceStartup ¶
ServiceStartup runs OnStart for all registered services that have one.
func (*Core) Startables ¶
Startables returns services that have an OnStart function.
func (*Core) Stoppables ¶
Stoppables returns services that have an OnStop function.
type CrashReport ¶
type CrashReport struct {
Timestamp time.Time `json:"timestamp"`
Error string `json:"error"`
Stack string `json:"stack"`
System CrashSystem `json:"system,omitempty"`
Meta map[string]string `json:"meta,omitempty"`
}
CrashReport represents a single crash event.
type CrashSystem ¶
type CrashSystem struct {
OperatingSystem string `json:"operatingsystem"`
Architecture string `json:"architecture"`
Version string `json:"go_version"`
}
CrashSystem holds system information at crash time.
type Data ¶
type Data struct {
// contains filtered or unexported fields
}
Data manages mounted embedded filesystems from core packages.
func (*Data) Extract ¶
Extract copies a template directory to targetDir.
r := c.Data().Extract("agent/workspace/default", "/tmp/ws", templateData)
func (*Data) Get ¶
Get returns the Embed for a named mount point.
r := c.Data().Get("brain")
if r.OK { emb := r.Value.(*Embed) }
func (*Data) List ¶
List returns directory entries at a path.
r := c.Data().List("agent/persona/code")
if r.OK { entries := r.Value.([]fs.DirEntry) }
func (*Data) ListNames ¶
ListNames returns filenames (without extensions) at a path.
r := c.Data().ListNames("agent/flow")
if r.OK { names := r.Value.([]string) }
func (*Data) New ¶
New registers an embedded filesystem under a named prefix.
c.Data().New(core.Options{
{Key: "name", Value: "brain"},
{Key: "source", Value: brainFS},
{Key: "path", Value: "prompts"},
})
func (*Data) ReadFile ¶
ReadFile reads a file by full path.
r := c.Data().ReadFile("brain/prompts/coding.md")
if r.OK { data := r.Value.([]byte) }
func (*Data) ReadString ¶
ReadString reads a file as a string.
r := c.Data().ReadString("agent/flow/deploy/to/homelab.yaml")
if r.OK { content := r.Value.(string) }
type Drive ¶
type Drive struct {
// contains filtered or unexported fields
}
Drive manages named transport handles.
func (*Drive) Get ¶
Get returns a handle by name.
r := c.Drive().Get("api")
if r.OK { handle := r.Value.(*DriveHandle) }
type DriveHandle ¶
DriveHandle holds a named transport resource.
type Embed ¶
type Embed struct {
// contains filtered or unexported fields
}
Embed wraps an fs.FS with a basedir for scoped access. All paths are relative to basedir.
func (*Embed) BaseDirectory ¶
BaseDirectory returns the base directory this Embed is anchored at.
func (*Embed) EmbedFS ¶
EmbedFS returns the underlying embed.FS if mounted from one. Returns zero embed.FS if mounted from a non-embed source.
func (*Embed) Open ¶
Open opens the named file for reading.
r := emb.Open("test.txt")
if r.OK { file := r.Value.(fs.File) }
func (*Embed) ReadFile ¶
ReadFile reads the named file.
r := emb.ReadFile("test.txt")
if r.OK { data := r.Value.([]byte) }
func (*Embed) ReadString ¶
ReadString reads the named file as a string.
r := emb.ReadString("test.txt")
if r.OK { content := r.Value.(string) }
type Err ¶
type Err struct {
Operation string // Operation being performed (e.g., "user.Save")
Message string // Human-readable message
Cause error // Underlying error (optional)
Code string // Error code (optional, e.g., "VALIDATION_FAILED")
}
Err represents a structured error with operational context. It implements the error interface and supports unwrapping.
type ErrorLog ¶
type ErrorLog struct {
// contains filtered or unexported fields
}
ErrorLog combines error creation with logging. Primary action: return an error. Secondary: log it.
type ErrorPanic ¶
type ErrorPanic struct {
// contains filtered or unexported fields
}
ErrorPanic manages panic recovery and crash reporting.
func (*ErrorPanic) Recover ¶
func (h *ErrorPanic) Recover()
Recover captures a panic and creates a crash report. Use as: defer c.Error().Recover()
func (*ErrorPanic) Reports ¶
func (h *ErrorPanic) Reports(n int) Result
Reports returns the last n crash reports from the file.
func (*ErrorPanic) SafeGo ¶
func (h *ErrorPanic) SafeGo(fn func())
SafeGo runs a function in a goroutine with panic recovery.
type ErrorSink ¶
ErrorSink is the shared interface for error reporting. Implemented by ErrorLog (structured logging) and ErrorPanic (panic recovery).
type ExtractOptions ¶
type ExtractOptions struct {
// TemplateFilters identifies template files by substring match.
// Default: [".tmpl"]
TemplateFilters []string
// IgnoreFiles is a set of filenames to skip during extraction.
IgnoreFiles map[string]struct{}
// RenameFiles maps original filenames to new names.
RenameFiles map[string]string
}
ExtractOptions configures template extraction.
type Fs ¶
type Fs struct {
// contains filtered or unexported fields
}
Fs is a sandboxed local filesystem backend.
func (*Fs) ReadStream ¶
ReadStream returns a reader for the file content.
func (*Fs) Write ¶
Write saves content to file, creating parent directories as needed. Files are created with mode 0644. For sensitive files (keys, secrets), use WriteMode with 0600.
func (*Fs) WriteMode ¶
WriteMode saves content to file with explicit permissions. Use 0600 for sensitive files (encryption output, private keys, auth hashes).
func (*Fs) WriteStream ¶
WriteStream returns a writer for the file content.
type I18n ¶
type I18n struct {
// contains filtered or unexported fields
}
I18n manages locale collection and translation dispatch.
func (*I18n) AddLocales ¶
AddLocales adds locale mounts (called during service registration).
func (*I18n) AvailableLanguages ¶
AvailableLanguages returns all loaded language codes.
func (*I18n) SetLanguage ¶
SetLanguage sets the active language and forwards to the translator if registered.
func (*I18n) SetTranslator ¶
func (i *I18n) SetTranslator(t Translator)
SetTranslator registers the translation implementation. Called by go-i18n's Srv during startup.
func (*I18n) Translate ¶
Translate translates a message. Returns the key as-is if no translator is registered.
func (*I18n) Translator ¶
Translator returns the registered translation implementation, or nil.
type Ipc ¶
type Ipc struct {
// contains filtered or unexported fields
}
Ipc holds IPC dispatch data.
type Level ¶
type Level int
Level defines logging verbosity.
const ( // LevelQuiet suppresses all log output. LevelQuiet Level = iota // LevelError shows only error messages. LevelError // LevelWarn shows warnings and errors. LevelWarn // LevelInfo shows informational messages, warnings, and errors. LevelInfo // LevelDebug shows all messages including debug details. LevelDebug )
Logging level constants ordered by increasing verbosity.
type LocaleProvider ¶
type LocaleProvider interface {
Locales() *Embed
}
LocaleProvider is implemented by services that ship their own translation files. Core discovers this interface during service registration and collects the locale mounts. The i18n service loads them during startup.
Usage in a service package:
//go:embed locales
var localeFS embed.FS
func (s *MyService) Locales() *Embed {
m, _ := Mount(localeFS, "locales")
return m
}
type Log ¶
type Log struct {
// Style functions for formatting (can be overridden)
StyleTimestamp func(string) string
StyleDebug func(string) string
StyleInfo func(string) string
StyleWarn func(string) string
StyleError func(string) string
StyleSecurity func(string) string
// contains filtered or unexported fields
}
Log provides structured logging.
func (*Log) Security ¶
Security logs a security event with optional key-value pairs. It uses LevelError to ensure security events are visible even in restrictive log configurations.
func (*Log) SetRedactKeys ¶
SetRedactKeys sets the keys to be redacted.
type LogErr ¶
type LogErr struct {
// contains filtered or unexported fields
}
LogErr logs structured information extracted from errors. Primary action: log. Secondary: extract error context.
type LogOptions ¶
type LogOptions struct {
Level Level
// Output is the destination for log messages. If Rotation is provided,
// Output is ignored and logs are written to the rotating file instead.
Output goio.Writer
// Rotation enables log rotation to file. If provided, Filename must be set.
Rotation *RotationLogOptions
// RedactKeys is a list of keys whose values should be masked in logs.
RedactKeys []string
}
LogOptions configures a Log.
type LogPanic ¶
type LogPanic struct {
// contains filtered or unexported fields
}
LogPanic logs panic context without crash file management. Primary action: log. Secondary: recover panics.
func NewLogPanic ¶
NewLogPanic creates a LogPanic bound to the given logger.
type Option ¶
Option is a single key-value configuration pair.
core.Option{Key: "name", Value: "brain"}
core.Option{Key: "port", Value: 8080}
type Options ¶
type Options []Option
Options is a collection of Option items. The universal input type for Core operations.
opts := core.Options{{Key: "name", Value: "myapp"}}
name := opts.String("name")
func (Options) Get ¶
Get retrieves a value by key.
r := opts.Get("name")
if r.OK { name := r.Value.(string) }
type QueryHandler ¶
QueryHandler handles Query requests. Returns Result{Value, OK}.
type Result ¶
Result is the universal return type for Core operations. Replaces the (value, error) pattern — errors flow through Core internally.
r := c.Data().New(core.Options{{Key: "name", Value: "brain"}})
if r.OK { use(r.Result()) }
func Arg ¶
Arg extracts a value from variadic args at the given index. Type-checks and delegates to the appropriate typed extractor. Returns Result — OK is false if index is out of bounds.
r := core.Arg(0, args...)
if r.OK { path = r.Value.(string) }
func Extract ¶
Extract copies a template directory from an fs.FS to targetDir, processing Go text/template in filenames and file contents.
Files containing a template filter substring (default: ".tmpl") have their contents processed through text/template with the given data. The filter is stripped from the output filename.
Directory and file names can contain Go template expressions: {{.Name}}/main.go → myproject/main.go
Data can be any struct or map[string]string for template substitution.
func Find ¶
Find locates a program on PATH and returns a Result containing the App.
r := core.Find("node", "Node.js")
if r.OK { app := r.Value.(*App) }
func GeneratePack ¶
func GeneratePack(pkg ScannedPackage) Result
GeneratePack creates Go source code that embeds the scanned assets.
func GetAsset ¶
GetAsset retrieves and decompresses a packed asset.
r := core.GetAsset("mygroup", "greeting")
if r.OK { content := r.Value.(string) }
func GetAssetBytes ¶
GetAssetBytes retrieves a packed asset as bytes.
r := core.GetAssetBytes("mygroup", "file")
if r.OK { data := r.Value.([]byte) }
func Mount ¶
Mount creates a scoped view of an fs.FS anchored at basedir.
r := core.Mount(myFS, "lib/prompts")
if r.OK { emb := r.Value.(*Embed) }
func MountEmbed ¶
MountEmbed creates a scoped view of an embed.FS.
r := core.MountEmbed(myFS, "testdata")
func NewRuntime ¶
NewRuntime creates a Runtime with no custom services.
func NewWithFactories ¶
func NewWithFactories(app any, factories map[string]ServiceFactory) Result
NewWithFactories creates a Runtime with the provided service factories.
func ScanAssets ¶
ScanAssets parses Go source files and finds asset references. Looks for calls to: core.GetAsset("group", "name"), core.AddAsset, etc.
type RotationLogOptions ¶
type RotationLogOptions struct {
// Filename is the log file path. If empty, rotation is disabled.
Filename string
// MaxSize is the maximum size of the log file in megabytes before it gets rotated.
// It defaults to 100 megabytes.
MaxSize int
// MaxAge is the maximum number of days to retain old log files based on their
// file modification time. It defaults to 28 days.
// Note: set to a negative value to disable age-based retention.
MaxAge int
// MaxBackups is the maximum number of old log files to retain.
// It defaults to 5 backups.
MaxBackups int
// Compress determines if the rotated log files should be compressed using gzip.
// It defaults to true.
Compress bool
}
RotationLogOptions defines the log rotation and retention policy.
type Runtime ¶
type Runtime struct {
Core *Core
// contains filtered or unexported fields
}
Runtime is the container for GUI runtimes (e.g., Wails).
func (*Runtime) ServiceName ¶
type ScannedPackage ¶
type ScannedPackage struct {
PackageName string
BaseDirectory string
Groups []string
Assets []AssetRef
}
ScannedPackage holds all asset references from a set of source files.
type Service ¶
type Service struct {
Name string
Options Options
OnStart func() Result
OnStop func() Result
OnReload func() Result
}
Service is a managed component with optional lifecycle.
type ServiceFactory ¶
type ServiceFactory func() Result
ServiceFactory defines a function that creates a Service.
type ServiceRuntime ¶
type ServiceRuntime[T any] struct { // contains filtered or unexported fields }
ServiceRuntime is embedded in services to provide access to the Core and typed options.
func NewServiceRuntime ¶
func NewServiceRuntime[T any](c *Core, opts T) *ServiceRuntime[T]
NewServiceRuntime creates a ServiceRuntime for a service constructor.
func (*ServiceRuntime[T]) Config ¶
func (r *ServiceRuntime[T]) Config() *Config
func (*ServiceRuntime[T]) Core ¶
func (r *ServiceRuntime[T]) Core() *Core
func (*ServiceRuntime[T]) Options ¶
func (r *ServiceRuntime[T]) Options() T
type TaskHandler ¶
TaskHandler handles Task requests. Returns Result{Value, OK}.
type TaskWithIdentifier ¶
TaskWithIdentifier is an optional interface for tasks that need to know their assigned identifier.
type Translator ¶
type Translator interface {
// Translate translates a message by its ID with optional arguments.
Translate(messageID string, args ...any) Result
// SetLanguage sets the active language (BCP47 tag, e.g., "en-GB", "de").
SetLanguage(lang string) error
// Language returns the current language code.
Language() string
// AvailableLanguages returns all loaded language codes.
AvailableLanguages() []string
}
Translator defines the interface for translation services. Implemented by go-i18n's Srv.