assetmin

package module
v0.0.68 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2025 License: MIT Imports: 20 Imported by: 0

README ยถ

๐Ÿ“ฆ AssetMin

Project Badges

๐Ÿš€ A lightweight and efficient web asset packager and minifier for Go applications

AssetMin bundles and minifies your JavaScript, CSS, SVG, and HTML files with support for both memory-based and disk-based serving. Perfect for development and production workflows.

๐Ÿ› ๏ธ Primary Use Case

AssetMin is primarily used in the GoDEV framework for developing full stack projects with Go. It provides an efficient solution for managing and optimizing web assets, ensuring seamless integration into your Go workflow.

โœจ Features

  • ๐Ÿ”„ Live Asset Processing - Event-driven file processing with automatic cache invalidation
  • ๐Ÿ—œ๏ธ Minification - Optimized minification using tdewolff/minify
  • ๐Ÿ’พ Dual Work Modes - Memory-only (dev) or disk-based (production) serving
  • ๐ŸŒ HTTP Serving - Built-in HTTP handlers with configurable URL prefixes
  • ๐Ÿ”’ Thread-Safe - Concurrent file processing with mutex protection
  • ๐Ÿ“ฆ Asset Bundling - Combines multiple files into optimized bundles
  • โšก Smart Caching - In-memory cache for instant HTTP responses

๐Ÿ“ฅ Installation

go get github.com/tinywasm/assetmin

๐Ÿš€ Quick Start

package main

import (
	"log"
	"net/http"
	
	"github.com/tinywasm/assetmin"
)

func main() {
	// Create configuration
	config := &assetmin.Config{
		OutputDir: "web/public",
		Logger: func(msg ...any) {
			log.Println(msg...)
		},
		AppName: "MyApp",
		AssetsURLPrefix: "/assets/",
	}
	
	// Initialize AssetMin
	am := assetmin.NewAssetMin(config)
	
	// Register HTTP routes
	mux := http.NewServeMux()
	am.RegisterRoutes(mux)
	
	// Process files
	am.NewFileEvent("button.css", ".css", "./src/button.css", "create")
	am.NewFileEvent("app.js", ".js", "./src/app.js", "create")
	
	// Start server
	log.Println("Server running on :8080")
	http.ListenAndServe(":8080", mux)
}

๐Ÿ”„ How It Works

  1. Configure - Set output directory and options
  2. Initialize - Create AssetMin instance
  3. Process Events - Notify AssetMin of file changes
  4. Serve - Assets are minified, cached, and served via HTTP
  5. Deploy - Switch to DiskMode to write optimized files

๐Ÿ“š Documentation

๐ŸŽฏ Core API

Configuration
type Config struct {
    OutputDir               string                 // Output directory for assets
    Logger                  func(message ...any)   // Logging function
    GetRuntimeInitializerJS func() (string, error) // JS initialization code
    AppName                 string                 // Application name
    AssetsURLPrefix         string                 // URL prefix for assets
}
Main Methods
// Create new instance
am := assetmin.NewAssetMin(config)

// Process file events
am.NewFileEvent(fileName, extension, filePath, event)

// Register HTTP routes
am.RegisterRoutes(mux)

// Work mode control
am.SetWorkMode(assetmin.DiskMode)    // Write to disk
am.SetWorkMode(assetmin.MemoryMode)  // Memory only (default)

// Manual asset refresh
am.RefreshAsset(".js")  // Rebuild JavaScript bundle

๐ŸŒ HTTP Routes

AssetMin automatically registers routes for all assets:

Asset Default Route With Prefix /assets/
index.html / /
style.css /style.css /assets/style.css
script.js /script.js /assets/script.js
sprite.svg /sprite.svg /assets/sprite.svg
favicon.svg /favicon.svg /assets/favicon.svg

๐Ÿ’พ Work Modes

MemoryMode (Default)
  • Serves assets from in-memory cache
  • No disk writes
  • Fastest for development
DiskMode
  • Writes assets to disk on changes
  • Still serves from cache for performance
  • Useful for production builds
// Development
am.SetWorkMode(assetmin.MemoryMode)

// Production
am.SetWorkMode(assetmin.DiskMode)
am.EnsureOutputDirectoryExists()

๐Ÿ“‹ Supported File Types

  • JavaScript (.js) - Bundled with automatic 'use strict' handling
  • CSS (.css) - Merged and minified stylesheets
  • SVG (.svg) - Icon sprites and favicons
  • HTML (.html) - Template fragments (complete documents ignored)

๐Ÿ”ง Advanced Usage

See the API Documentation for:

  • WASM integration examples
  • File watcher integration
  • Development vs production setup
  • Thread safety details
  • Performance considerations

๐Ÿ“‹ Roadmap

  • โœ… Config Simplification
  • โœ… Asset Caching System
  • โœ… HTTP Routes & Work Modes
  • ๐Ÿ”„ Template System Refactor
  • ๐Ÿ”„ TUI Integration
  • ๐Ÿ”„ Enhanced SSR Support

See docs/ROADMAP.md for details.


๐Ÿ“„ License

This project is licensed under the [MIT] License.

Documentation ยถ

Index ยถ

Constants ยถ

This section is empty.

Variables ยถ

This section is empty.

Functions ยถ

func FileWrite ยถ

func FileWrite(pathFile string, data bytes.Buffer) error

pathFile e.g., "theme/htmlMainFileName" data e.g., *bytes.Buffer NOTE: The buffer data will be cleared after writing the file

func NewFaviconSvgHandler ยถ

func NewFaviconSvgHandler(ac *Config, outputName string) *asset

NewFaviconSvgHandler creates a handler for favicon.svg that simply minifies and copies the file without sprite wrapping. This handler processes standalone SVG files like favicon.svg

func NewHtmlHandler ยถ

func NewHtmlHandler(ac *Config, outputName, cssURL, jsURL string) *asset

NewHtmlHandler creates an HTML asset handler using the provided output filename

func NewSvgHandler ยถ

func NewSvgHandler(ac *Config, outputName string) *asset

Types ยถ

type AssetMin ยถ

type AssetMin struct {
	*Config
	// contains filtered or unexported fields
}

func NewAssetMin ยถ

func NewAssetMin(ac *Config) *AssetMin

func (*AssetMin) EnsureOutputDirectoryExists ยถ

func (c *AssetMin) EnsureOutputDirectoryExists()

func (*AssetMin) GetWorkMode ยถ

func (c *AssetMin) GetWorkMode() WorkMode

GetWorkMode returns the current work mode of AssetMin.

func (*AssetMin) NewFileEvent ยถ

func (c *AssetMin) NewFileEvent(fileName, extension, filePath, event string) error

event: create, remove, write, rename

func (*AssetMin) RefreshAsset ยถ

func (c *AssetMin) RefreshAsset(extension string)

func (*AssetMin) RegisterRoutes ยถ

func (c *AssetMin) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers the HTTP handlers for all assets.

func (*AssetMin) SetWorkMode ยถ

func (c *AssetMin) SetWorkMode(mode WorkMode)

SetWorkMode sets the work mode for AssetMin.

func (*AssetMin) SupportedExtensions ยถ

func (c *AssetMin) SupportedExtensions() []string

func (*AssetMin) UnobservedFiles ยถ

func (c *AssetMin) UnobservedFiles() []string

func (*AssetMin) UpdateFileContentInMemory ยถ

func (c *AssetMin) UpdateFileContentInMemory(filePath, extension, event string, content []byte) (*asset, error)

type Config ยถ

type Config struct {
	OutputDir               string                 // eg: web/static, web/public, web/assets
	Logger                  func(message ...any)   // Renamed from io.Writer to a function type
	GetRuntimeInitializerJS func() (string, error) // javascript code to initialize the wasm or other handlers
	AppName                 string                 // Application name for templates (default: "MyApp")
	AssetsURLPrefix         string                 // New: for HTTP routes
}

type TestEnvironment ยถ

type TestEnvironment struct {
	BaseDir       string
	ThemeDir      string
	PublicDir     string
	ModulesDir    string
	MainJsPath    string
	MainCssPath   string
	MainSvgPath   string
	MainHtmlPath  string
	AssetsHandler *AssetMin
	// contains filtered or unexported fields
}

TestEnvironment holds all the paths and components needed for asset tests

func (*TestEnvironment) CleanDirectory ยถ

func (env *TestEnvironment) CleanDirectory()

CleanDirectory removes all content from the test directory but keeps the directory itself

func (*TestEnvironment) CreateModulesDir ยถ

func (env *TestEnvironment) CreateModulesDir() *TestEnvironment

CreateModulesDir creates the modules directory if it doesn't exist

func (*TestEnvironment) CreatePublicDir ยถ

func (env *TestEnvironment) CreatePublicDir() *TestEnvironment

CreatePublicDir creates the public directory if it doesn't exist

func (*TestEnvironment) CreateThemeDir ยถ

func (env *TestEnvironment) CreateThemeDir() *TestEnvironment

CreateThemeDir creates the theme directory if it doesn't exist

func (*TestEnvironment) TestConcurrentFileProcessing ยถ

func (env *TestEnvironment) TestConcurrentFileProcessing(fileExtension string, fileCount int)

TestConcurrentFileProcessing is a reusable function to test concurrent file processing for both JS and CSS.

func (*TestEnvironment) TestFileCRUDOperations ยถ

func (env *TestEnvironment) TestFileCRUDOperations(fileExtension string)

TestFileCRUDOperations tests the complete CRUD cycle (create, write, remove) for a file

type WorkMode ยถ

type WorkMode int
const (
	MemoryMode WorkMode = iota // Serve from memory cache (default)
	DiskMode                   // Write to disk + serve from cache
)

Jump to

Keyboard shortcuts

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