assets

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: 24 Imported by: 0

README

ForgeUI Assets Package

Production-ready static asset management with fingerprinting, caching, and embedded filesystem support


Features

  • Content-Based Fingerprinting: Automatic cache busting using SHA256 hashes
  • Intelligent Caching: Immutable cache for fingerprinted assets (1 year), moderate cache for dev
  • Security: Path traversal protection, proper MIME types, optional SRI
  • Embedded FS Support: Single-binary deployments with embed.FS
  • Manifest System: Pre-computed hashes for production builds
  • Dev/Prod Modes: Zero-config development, optimized production
  • Thread-Safe: Concurrent asset serving with RWMutex protection

Quick Start

Basic Usage
package main

import (
    "net/http"
    "github.com/xraph/forgeui"
)

func main() {
    // Initialize ForgeUI app
    app := forgeui.New(
        forgeui.WithDebug(true),              // Dev mode
        forgeui.WithAssetPublicDir("public"),  // Assets directory
    )

    // Serve static files through asset pipeline
    http.Handle("/static/", app.Assets.Handler())

    http.ListenAndServe(":8080", nil)
}
In HTML Templates
// CSS Stylesheets
app.Assets.StyleSheet("css/app.css")
app.Assets.StyleSheet("css/print.css", assets.WithMedia("print"))

// JavaScript
app.Assets.Script("js/app.js", assets.WithDefer())
app.Assets.Script("js/module.js", assets.WithModule())

// Inline CSS/JS
assets.InlineCSS("body { margin: 0; }")
assets.InlineScript("console.log('hello');")

Development vs Production

Development Mode
app := forgeui.New(forgeui.WithDebug(true))
  • No fingerprinting: URLs remain simple (/static/app.css)
  • Moderate caching: Cache-Control: public, max-age=3600
  • Fast iteration: No build step required
Production Mode
app := forgeui.New(forgeui.WithDebug(false))
  • Automatic fingerprinting: URLs include content hash (/static/app.abc12345.css)
  • Immutable caching: Cache-Control: public, max-age=31536000, immutable
  • Optimal performance: 1-year browser cache

Manifest System

For production builds, pre-compute fingerprints to eliminate runtime I/O:

Generate Manifest
package main

import (
    "github.com/xraph/forgeui/assets"
)

func main() {
    m := assets.NewManager(assets.Config{
        PublicDir: "public",
        IsDev:     false,
    })

    // Generate manifest for all assets
    manifest, err := assets.GenerateManifest(m)
    if err != nil {
        panic(err)
    }

    // Save to file
    if err := manifest.Save("dist/manifest.json"); err != nil {
        panic(err)
    }
}
Use Manifest
app := forgeui.New(
    forgeui.WithAssetManifest("dist/manifest.json"),
)

Manifest Format (manifest.json):

{
  "css/app.css": "css/app.abc12345.css",
  "js/main.js": "js/main.def67890.js"
}

Embedded Filesystem

For single-binary deployments:

package main

import (
    "embed"
    "net/http"
    "github.com/xraph/forgeui/assets"
)

//go:embed static/*
var staticFS embed.FS

func main() {
    m := assets.NewEmbeddedManager(staticFS, assets.Config{
        PublicDir: "static",
        IsDev:     false,
    })

    // Pre-generate fingerprints
    m.FingerprintAllEmbedded()

    // Serve from embedded FS
    http.Handle("/static/", m.EmbeddedHandler())
    
    http.ListenAndServe(":8080", nil)
}

API Reference

Manager
type Manager struct {
    // ...
}

func NewManager(cfg Config) *Manager

// URL returns the URL for an asset (with fingerprint in production)
func (m *Manager) URL(path string) string

// Handler returns an http.Handler for serving static files
func (m *Manager) Handler() http.Handler

// StyleSheet creates a <link> element for CSS
func (m *Manager) StyleSheet(path string, opts ...StyleOption) g.Node

// Script creates a <script> element for JavaScript
func (m *Manager) Script(path string, opts ...ScriptOption) g.Node

// FingerprintAll generates fingerprints for all assets
func (m *Manager) FingerprintAll() error

// SaveManifest writes fingerprint mappings to a file
func (m *Manager) SaveManifest(path string) error
Configuration
type Config struct {
    PublicDir  string // Source directory (default: "public")
    OutputDir  string // Output directory (default: "dist")
    IsDev      bool   // Development mode
    Manifest   string // Manifest file path
}
Style Options
assets.WithMedia("print")              // media attribute
assets.WithPreload()                   // preload the stylesheet
assets.WithIntegrity("sha256-...")     // SRI hash
assets.WithCrossOrigin("anonymous")    // CORS
Script Options
assets.WithDefer()                     // defer attribute
assets.WithAsync()                     // async attribute
assets.WithModule()                    // type="module"
assets.WithScriptIntegrity("sha256-...") // SRI hash
assets.WithScriptCrossOrigin("anonymous") // CORS
assets.WithNoModule()                  // nomodule fallback

Examples

Preloading Assets
// Preload critical CSS
app.Assets.PreloadStyleSheet("css/critical.css")
app.Assets.StyleSheet("css/critical.css")

// Preload critical JS
app.Assets.PreloadScript("js/critical.js")
app.Assets.Script("js/critical.js", assets.WithDefer())
Media Queries
// Screen styles
app.Assets.StyleSheet("css/screen.css", assets.WithMedia("screen"))

// Print styles
app.Assets.StyleSheet("css/print.css", assets.WithMedia("print"))
ES Modules
// Modern browsers
app.Assets.Script("js/app.js", assets.WithModule())

// Legacy fallback
app.Assets.Script("js/app.legacy.js", assets.WithNoModule())
Subresource Integrity (SRI)
app.Assets.StyleSheet(
    "css/app.css",
    assets.WithIntegrity("sha256-abc123..."),
    assets.WithCrossOrigin("anonymous"),
)

Security

Path Traversal Protection

All paths are validated to prevent directory traversal attacks:

// ✅ Valid
app.Assets.URL("css/app.css")
app.Assets.URL("js/vendor/lib.js")

// ❌ Blocked
app.Assets.URL("../../../etc/passwd")
app.Assets.URL("../config.json")
MIME Type Detection

Proper Content-Type headers are set automatically based on file extension to prevent XSS attacks.

Optional SRI

Subresource Integrity (SRI) hashes can be added for CDN fallbacks:

app.Assets.StyleSheet(
    "css/app.css",
    assets.WithIntegrity("sha256-..."),
)

Performance

Caching Strategy
Asset Type Cache-Control Duration
Fingerprinted (prod) public, max-age=31536000, immutable 1 year
Non-fingerprinted public, max-age=3600 1 hour
Dev mode public, max-age=3600 1 hour
Thread Safety

The asset manager uses sync.RWMutex for thread-safe concurrent access:

  • Multiple concurrent reads
  • Exclusive writes
  • Zero-allocation fingerprint lookups
Manifest Pre-loading

Loading a manifest eliminates runtime I/O in production:

  • No disk reads during request handling
  • Instant URL generation
  • Reduced latency

Testing

Run tests with coverage:

go test ./assets/... -cover

Expected coverage: >85%


License

MIT License - see LICENSE file for details

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InlineCSS

func InlineCSS(content string) g.Node

InlineCSS creates a <style> element with inline CSS content

func InlineCSSWithAttrs

func InlineCSSWithAttrs(content string, attrs ...g.Node) g.Node

InlineCSSWithAttrs creates a <style> element with inline CSS and custom attributes

func InlineScript

func InlineScript(content string) g.Node

InlineScript creates a <script> element with inline JavaScript content

func InlineScriptWithAttrs

func InlineScriptWithAttrs(content string, attrs ...g.Node) g.Node

InlineScriptWithAttrs creates a <script> element with inline JavaScript and custom attributes

Types

type Config

type Config struct {
	// PublicDir is the source directory for static assets (e.g., "public")
	PublicDir string

	// OutputDir is the output directory for processed assets (e.g., "dist")
	OutputDir string

	// IsDev enables development mode (no fingerprinting)
	IsDev bool

	// Manifest is the path to a manifest file for production builds
	Manifest string
}

Config defines configuration options for asset management

type DevServer

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

DevServer provides development features like hot reload and file watching. It watches for file changes and notifies connected browsers via Server-Sent Events (SSE).

func NewDevServer

func NewDevServer(pipeline *Pipeline) (*DevServer, error)

NewDevServer creates a new development server

func (*DevServer) ClientCount

func (ds *DevServer) ClientCount() int

ClientCount returns the number of connected SSE clients

func (*DevServer) Close

func (ds *DevServer) Close() error

Close stops the dev server and releases resources

func (*DevServer) HotReloadScript

func (ds *DevServer) HotReloadScript() string

HotReloadScript returns the client-side JavaScript for hot reload

func (*DevServer) SSEHandler

func (ds *DevServer) SSEHandler() http.HandlerFunc

SSEHandler returns an HTTP handler for Server-Sent Events

func (*DevServer) SetVerbose

func (ds *DevServer) SetVerbose(verbose bool)

SetVerbose enables verbose logging

func (*DevServer) Start

func (ds *DevServer) Start(ctx context.Context) error

Start begins the development server with file watching and hot reload

type ESBuildProcessor

type ESBuildProcessor struct {
	// EntryPoints are the JavaScript entry files to bundle
	EntryPoints []string

	// Outfile is the output bundle file path (relative to output directory)
	Outfile string

	// Format specifies the output format ("iife", "cjs", "esm")
	Format string

	// Target specifies the JavaScript target (e.g., "es2020")
	Target string

	// Bundle enables bundling of dependencies
	Bundle bool

	// Splitting enables code splitting (requires format: "esm")
	Splitting bool

	// External are packages to exclude from bundling
	External []string

	// Verbose enables detailed logging
	Verbose bool
}

ESBuildProcessor bundles and minifies JavaScript files using esbuild. It's optional for SSR applications but useful for custom JavaScript.

func NewESBuildProcessor

func NewESBuildProcessor() *ESBuildProcessor

NewESBuildProcessor creates a new ESBuild processor with sensible defaults

func (*ESBuildProcessor) FileTypes

func (ep *ESBuildProcessor) FileTypes() []string

FileTypes returns the file extensions this processor handles

func (*ESBuildProcessor) Name

func (ep *ESBuildProcessor) Name() string

Name returns the processor name

func (*ESBuildProcessor) Process

func (ep *ESBuildProcessor) Process(ctx context.Context, cfg ProcessorConfig) error

Process executes the ESBuild bundling

func (*ESBuildProcessor) WithBundle

func (ep *ESBuildProcessor) WithBundle(bundle bool) *ESBuildProcessor

WithBundle enables or disables bundling

func (*ESBuildProcessor) WithEntryPoints

func (ep *ESBuildProcessor) WithEntryPoints(entries ...string) *ESBuildProcessor

WithEntryPoints sets the JavaScript entry points

func (*ESBuildProcessor) WithExternal

func (ep *ESBuildProcessor) WithExternal(external ...string) *ESBuildProcessor

WithExternal sets packages to exclude from bundling

func (*ESBuildProcessor) WithFormat

func (ep *ESBuildProcessor) WithFormat(format string) *ESBuildProcessor

WithFormat sets the output format

func (*ESBuildProcessor) WithOutfile

func (ep *ESBuildProcessor) WithOutfile(path string) *ESBuildProcessor

WithOutfile sets the output bundle file path

func (*ESBuildProcessor) WithSplitting

func (ep *ESBuildProcessor) WithSplitting(splitting bool) *ESBuildProcessor

WithSplitting enables code splitting

func (*ESBuildProcessor) WithTarget

func (ep *ESBuildProcessor) WithTarget(target string) *ESBuildProcessor

WithTarget sets the JavaScript target

func (*ESBuildProcessor) WithVerbose

func (ep *ESBuildProcessor) WithVerbose(verbose bool) *ESBuildProcessor

WithVerbose enables verbose logging

type EmbeddedManager

type EmbeddedManager struct {
	*Manager
	// contains filtered or unexported fields
}

EmbeddedManager extends Manager to work with embed.FS

func NewEmbeddedManager

func NewEmbeddedManager(embedFS fs.FS, cfg Config) *EmbeddedManager

NewEmbeddedManager creates a manager that serves assets from an embedded filesystem

func (*EmbeddedManager) EmbeddedHandler

func (m *EmbeddedManager) EmbeddedHandler() http.Handler

EmbeddedHandler returns an http.Handler for serving embedded static files

func (*EmbeddedManager) FingerprintAllEmbedded

func (m *EmbeddedManager) FingerprintAllEmbedded() error

FingerprintAllEmbedded generates fingerprints for all embedded assets

type Manager

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

Manager handles static assets with caching and fingerprinting

func NewManager

func NewManager(cfg Config) *Manager

NewManager creates a new asset manager with the given configuration

func (*Manager) Build

func (m *Manager) Build(ctx context.Context) error

Build runs the asset pipeline to process all assets. This is typically used for production builds.

func (*Manager) FingerprintAll

func (m *Manager) FingerprintAll() error

FingerprintAll generates fingerprints for all assets in the public directory

func (*Manager) Handler

func (m *Manager) Handler() http.Handler

Handler returns an http.Handler for serving static files

func (*Manager) HotReloadScript

func (m *Manager) HotReloadScript() string

HotReloadScript returns the client-side JavaScript for hot reload. Include this in your HTML during development.

func (*Manager) IsDev

func (m *Manager) IsDev() bool

IsDev returns whether the manager is in development mode

func (*Manager) Pipeline

func (m *Manager) Pipeline() *Pipeline

Pipeline returns the asset pipeline for this manager. Creates a new pipeline if one doesn't exist.

func (*Manager) PreloadScript

func (m *Manager) PreloadScript(path string, opts ...ScriptOption) g.Node

PreloadScript creates a <link rel="preload"> element for a JavaScript file

func (*Manager) PreloadStyleSheet

func (m *Manager) PreloadStyleSheet(path string, opts ...StyleOption) g.Node

PreloadStyleSheet creates a <link rel="preload"> element for a CSS file

func (*Manager) PublicDir

func (m *Manager) PublicDir() string

PublicDir returns the configured public directory

func (*Manager) SSEHandler

func (m *Manager) SSEHandler() any

SSEHandler returns the Server-Sent Events handler for hot reload. Mount this at /_forgeui/reload in your HTTP server. Returns nil if dev server is not running.

func (*Manager) SaveManifest

func (m *Manager) SaveManifest(path string) error

SaveManifest writes the current fingerprint mappings to a manifest file

func (*Manager) Script

func (m *Manager) Script(path string, opts ...ScriptOption) g.Node

Script creates a <script> element for a JavaScript file

func (*Manager) StartDevServer

func (m *Manager) StartDevServer(ctx context.Context) error

StartDevServer starts the development server with hot reload. This watches for file changes and automatically rebuilds assets.

func (*Manager) StopDevServer

func (m *Manager) StopDevServer() error

StopDevServer stops the development server if running

func (*Manager) StyleSheet

func (m *Manager) StyleSheet(path string, opts ...StyleOption) g.Node

StyleSheet creates a <link> element for a CSS file

func (*Manager) URL

func (m *Manager) URL(path string) string

URL returns the URL for an asset, with fingerprint in production

type Manifest

type Manifest map[string]string

Manifest represents a mapping of original asset paths to fingerprinted paths

func GenerateManifest

func GenerateManifest(m *Manager) (Manifest, error)

GenerateManifest creates a manifest from all assets in a directory

func LoadManifest

func LoadManifest(path string) (Manifest, error)

LoadManifest loads a manifest from a JSON file

func (Manifest) Get

func (manifest Manifest) Get(path string) (string, bool)

Get retrieves a fingerprinted path from the manifest

func (Manifest) Save

func (manifest Manifest) Save(path string) error

Save writes the manifest to a JSON file

func (Manifest) Set

func (manifest Manifest) Set(path, fingerprinted string)

Set adds or updates a mapping in the manifest

type Pipeline

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

Pipeline orchestrates multiple asset processors in sequence. It ensures processors run in the correct order and handles errors gracefully.

func NewPipeline

func NewPipeline(cfg PipelineConfig, manager *Manager) *Pipeline

NewPipeline creates a new asset pipeline with the given configuration

func (*Pipeline) AddProcessor

func (p *Pipeline) AddProcessor(processor Processor) *Pipeline

AddProcessor adds a processor to the pipeline. Processors are executed in the order they are added.

func (*Pipeline) Build

func (p *Pipeline) Build(ctx context.Context) error

Build executes all processors in sequence. If any processor fails, the build stops and returns the error.

func (*Pipeline) Config

func (p *Pipeline) Config() PipelineConfig

Config returns the pipeline configuration

func (*Pipeline) ProcessorCount

func (p *Pipeline) ProcessorCount() int

ProcessorCount returns the number of processors in the pipeline

func (*Pipeline) Processors

func (p *Pipeline) Processors() []Processor

Processors returns a copy of the processor list

type PipelineConfig

type PipelineConfig struct {
	// InputDir is the source directory for all assets
	InputDir string

	// OutputDir is the destination directory for processed assets
	OutputDir string

	// IsDev enables development mode (no minification, faster builds)
	IsDev bool

	// Minify enables minification of assets in production
	Minify bool

	// SourceMaps enables source map generation
	SourceMaps bool

	// Watch enables file watching for automatic rebuilds
	Watch bool

	// CleanOutput removes the output directory before building
	CleanOutput bool

	// Verbose enables detailed logging
	Verbose bool
}

PipelineConfig defines the pipeline's overall configuration

type Processor

type Processor interface {
	// Name returns the processor name for logging and debugging
	Name() string

	// Process executes the asset processing with the given configuration
	Process(ctx context.Context, cfg ProcessorConfig) error

	// FileTypes returns the file extensions this processor handles (e.g., [".css", ".js"])
	FileTypes() []string
}

Processor processes assets (CSS, JS, images, etc.) Implementations can handle different asset types and transformations.

type ProcessorConfig

type ProcessorConfig struct {
	// InputDir is the source directory for assets
	InputDir string

	// OutputDir is the destination directory for processed assets
	OutputDir string

	// IsDev indicates if running in development mode
	IsDev bool

	// Minify enables minification of assets
	Minify bool

	// SourceMaps enables source map generation
	SourceMaps bool

	// Watch enables file watching for automatic rebuilds
	Watch bool

	// CustomConfig allows processors to receive custom configuration
	CustomConfig map[string]any
}

ProcessorConfig contains configuration for asset processing

type ScriptEntry

type ScriptEntry struct {
	// Path is the URL or file path to the script
	Path string

	// Priority determines load order (0-100, lower loads first)
	// Typical values:
	//   0-19: Critical framework scripts (Alpine.js, etc.)
	//   20-49: Library dependencies
	//   50-79: Application scripts
	//   80-100: Analytics, third-party widgets
	Priority int

	// Position determines where the script is rendered ("head" or "body")
	Position string

	// Inline indicates if this is an inline script (Content is used instead of Path)
	Inline bool

	// Content is the inline script content (only used if Inline is true)
	Content string

	// Attrs are additional HTML attributes (defer, async, type, etc.)
	Attrs map[string]string
}

ScriptEntry represents a script with metadata for ordering and rendering. Scripts can be inline or external, and are prioritized for optimal loading.

type ScriptManager

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

ScriptManager manages script loading order and rendering. It ensures scripts are loaded in the correct order based on priority and prevents duplicate script tags.

func NewScriptManager

func NewScriptManager() *ScriptManager

NewScriptManager creates a new script manager

func (*ScriptManager) Add

func (sm *ScriptManager) Add(entry ScriptEntry)

Add adds a script entry to the manager. Duplicate paths are ignored (first occurrence wins).

func (*ScriptManager) AddInline

func (sm *ScriptManager) AddInline(content string, priority int, position string)

AddInline adds an inline script with the given content

func (*ScriptManager) AddWithPriority

func (sm *ScriptManager) AddWithPriority(path string, priority int, attrs map[string]string)

AddWithPriority is a convenience method to add a script with a specific priority

func (*ScriptManager) Clear

func (sm *ScriptManager) Clear()

Clear removes all scripts from the manager

func (*ScriptManager) Count

func (sm *ScriptManager) Count() int

Count returns the total number of scripts

func (*ScriptManager) CountByPosition

func (sm *ScriptManager) CountByPosition(position string) int

CountByPosition returns the number of scripts in a specific position

func (*ScriptManager) Render

func (sm *ScriptManager) Render(position string) []g.Node

Render generates script tags for the specified position ("head" or "body"). Scripts are sorted by priority (lower numbers first) before rendering.

type ScriptOption

type ScriptOption func(*scriptConfig)

ScriptOption is a functional option for configuring script elements

func WithAsync

func WithAsync() ScriptOption

WithAsync sets the async attribute for a script

func WithDefer

func WithDefer() ScriptOption

WithDefer sets the defer attribute for a script

func WithModule

func WithModule() ScriptOption

WithModule sets type="module" for a script

func WithNoModule

func WithNoModule() ScriptOption

WithNoModule sets the nomodule attribute for a script

func WithScriptCrossOrigin

func WithScriptCrossOrigin(value string) ScriptOption

WithScriptCrossOrigin sets the crossorigin attribute for a script

func WithScriptIntegrity

func WithScriptIntegrity(hash string) ScriptOption

WithScriptIntegrity sets the integrity hash (SRI) for a script

type StyleOption

type StyleOption func(*styleConfig)

StyleOption is a functional option for configuring stylesheet elements

func WithCrossOrigin

func WithCrossOrigin(value string) StyleOption

WithCrossOrigin sets the crossorigin attribute for a stylesheet

func WithIntegrity

func WithIntegrity(hash string) StyleOption

WithIntegrity sets the integrity hash (SRI) for a stylesheet

func WithMedia

func WithMedia(media string) StyleOption

WithMedia sets the media attribute for a stylesheet

func WithPreload

func WithPreload() StyleOption

WithPreload enables preloading for a stylesheet

type TailwindProcessor

type TailwindProcessor struct {
	// ConfigPath is the path to tailwind.config.js (auto-generated if empty)
	ConfigPath string

	// InputCSS is the path to the input CSS file with @tailwind directives
	InputCSS string

	// OutputCSS is the path where processed CSS will be written
	OutputCSS string

	// ContentPaths are glob patterns for files to scan for classes
	// Defaults to ["**/*.go"] to scan all Go files
	ContentPaths []string

	// UseCDN falls back to CDN if Tailwind CLI is not available
	UseCDN bool

	// Verbose enables detailed logging
	Verbose bool
}

TailwindProcessor processes Tailwind CSS by scanning Go files for class usage and generating optimized CSS output.

func NewTailwindProcessor

func NewTailwindProcessor() *TailwindProcessor

NewTailwindProcessor creates a new Tailwind CSS processor with sensible defaults

func (*TailwindProcessor) FileTypes

func (tp *TailwindProcessor) FileTypes() []string

FileTypes returns the file extensions this processor handles

func (*TailwindProcessor) Name

func (tp *TailwindProcessor) Name() string

Name returns the processor name

func (*TailwindProcessor) Process

func (tp *TailwindProcessor) Process(ctx context.Context, cfg ProcessorConfig) error

Process executes the Tailwind CSS processing

func (*TailwindProcessor) WithConfigPath

func (tp *TailwindProcessor) WithConfigPath(path string) *TailwindProcessor

WithConfigPath sets a custom tailwind.config.js path

func (*TailwindProcessor) WithContentPaths

func (tp *TailwindProcessor) WithContentPaths(paths []string) *TailwindProcessor

WithContentPaths sets custom content paths to scan for classes

func (*TailwindProcessor) WithInputCSS

func (tp *TailwindProcessor) WithInputCSS(path string) *TailwindProcessor

WithInputCSS sets a custom input CSS file

func (*TailwindProcessor) WithOutputCSS

func (tp *TailwindProcessor) WithOutputCSS(path string) *TailwindProcessor

WithOutputCSS sets the output CSS file path (relative to output directory)

func (*TailwindProcessor) WithVerbose

func (tp *TailwindProcessor) WithVerbose(verbose bool) *TailwindProcessor

WithVerbose enables verbose logging

type WatchCallback

type WatchCallback func(event fsnotify.Event) error

WatchCallback is called when files change

type Watcher

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

Watcher watches files for changes and triggers callbacks. It uses fsnotify for cross-platform file system notifications.

func NewWatcher

func NewWatcher() (*Watcher, error)

NewWatcher creates a new file watcher

func (*Watcher) AddPath

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

AddPath adds a path to watch (file or directory)

func (*Watcher) AddPattern

func (w *Watcher) AddPattern(pattern string)

AddPattern adds a glob pattern for file matching

func (*Watcher) Close

func (w *Watcher) Close() error

Close stops the watcher and releases resources

func (*Watcher) OnChange

func (w *Watcher) OnChange(callback WatchCallback)

OnChange registers a callback for file changes

func (*Watcher) SetDebounce

func (w *Watcher) SetDebounce(duration time.Duration)

SetDebounce sets the debounce duration for file changes

func (*Watcher) SetVerbose

func (w *Watcher) SetVerbose(verbose bool)

SetVerbose enables verbose logging

func (*Watcher) Start

func (w *Watcher) Start(ctx context.Context) error

Start begins watching for file changes

func (*Watcher) WatchDirectory

func (w *Watcher) WatchDirectory(dir string) error

WatchDirectory recursively watches a directory and its subdirectories

Jump to

Keyboard shortcuts

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