gonify

package module
v2.0.6 Latest Latest
Warning

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

Go to latest
Published: May 23, 2025 License: MIT Imports: 14 Imported by: 0

README

✨ Gonify Middleware for Fiber ⚡

Go Report Card GoDoc License Fiber

A Fiber middleware that automatically minifies HTTP responses before sending them to clients. Powered by the efficient tdewolff/minify/v2 library.

🔹 Reduces transferred data size 🔹 Saves bandwidth 🔹 Improves page load times

🚀 Features

  • ✅ Automatic minification for HTML, CSS, JS, JSON, XML, and SVG responses
  • ⚙️ Easy configuration to enable/disable specific minification types
  • ⏭️ Next option to skip middleware for specific routes/conditions
  • 🛡️ Safe error handling - original response sent if minification fails
  • 🧩 Seamless Fiber v2 integration
  • 📝 Built-in Fiber logger for warnings/errors

📦 Installation

go get github.com/NarmadaWeb/gonify/v2

🛠️ Usage

Basic Usage (Default Configuration)

The simplest way is using default configuration which enables minification for all supported content types.

package main

import (
    "log"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/logger"
    "github.com/NarmadaWeb/gonify/v2"
)

func main() {
    app := fiber.New()
    app.Use(logger.New()) // Optional: logger

    // Use gonify middleware with default config
    app.Use(gonify.New())

    // Define your routes
    app.Get("/", func(c *fiber.Ctx) error {
        c.Set(fiber.HeaderContentType, fiber.MIMETextHTMLCharsetUTF8)
        htmlContent := "<html><body><h1>Hello, Minified World!</h1></body></html>"
        return c.SendString(htmlContent)
    })

    app.Get("/styles.css", func(c *fiber.Ctx) error {
        c.Set(fiber.HeaderContentType, "text/css; charset=utf-8")
        cssContent := "body { /* comment */ color: #ff0000; padding: 10px; }"
        return c.SendString(cssContent)
    })

    app.Get("/data.json", func(c *fiber.Ctx) error {
        c.Set(fiber.HeaderContentType, fiber.MIMEApplicationJSON)
        jsonContent := `{ "message": "This is   extra   spaced   JSON." }`
        return c.SendString(jsonContent)
    })

    log.Fatal(app.Listen(":3000"))
}
🔧 Custom Configuration

Provide a minify.Config struct to New() for custom behavior.

package main

import (
    "log"
    "strings"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/logger"
    "github.com/NarmadaWeb/gonify/v2"
)

func main() {
    app := fiber.New()
    app.Use(logger.New())

    app.Use(gonify.New(gonify.Config{
        MinifyHTML:       true,
        MinifyCSS:        true,
        MinifyJS:         false, // Disable JS minification
        MinifyJSON:       true,
        MinifyXML:        false, // Disable XML minification
        MinifySVG:        true,
        SuppressWarnings: false,
        Next: func(c *fiber.Ctx) bool {
            // Skip minification for paths starting with /api/raw/
            return strings.HasPrefix(c.Path(), "/api/raw/")
        },
    }))

    app.Get("/", func(c *fiber.Ctx) error {
        c.Set(fiber.HeaderContentType, fiber.MIMETextHTMLCharsetUTF8)
        // Example HTML string
        html := "<html><!-- comment --><body><h1>Will be minified</h1></body></html>"
        return c.SendString(html)
    })

    app.Get("/script.js", func(c *fiber.Ctx) error {
        c.Set(fiber.HeaderContentType, fiber.MIMEApplicationJavaScriptCharsetUTF8)
        // Example JS string
        js := "function hello() { /* comment */ console.log('Not minified'); }"
        return c.SendString(js)
    })

    app.Get("/api/raw/data", func(c *fiber.Ctx) error {
        c.Set(fiber.HeaderContentType, fiber.MIMEApplicationJSON)
        // Example JSON string that will not be minified due to Next config
        jsonStr := `{ "raw": true,    "spacing": "preserved" }`
        return c.SendString(jsonStr)
    })

    log.Fatal(app.Listen(":3000"))
}

⚙️ Configuration

Configure the middleware using minify.Config struct:

type Config struct {
    // Next: Function to determine if middleware should be skipped
    // Returns true to skip middleware for the request
    // Default: nil (always run)
    Next func(c *fiber.Ctx) bool

    // SuppressWarnings: If true, minification errors will be logged
    // as WARN and original response sent. If false (default), errors
    // will be logged as ERROR and original response sent.
    // Default: false
    SuppressWarnings bool

    // MinifyHTML: Enable for 'text/html'
    // Default: true
    MinifyHTML bool

    // MinifyCSS: Enable for 'text/css'
    // Default: true
    MinifyCSS bool

    // MinifyJS: Enable for JavaScript content types
    // (e.g., 'application/javascript', 'text/javascript')
    // Default: true
    MinifyJS bool

    // MinifyJSON: Enable for JSON content types (e.g., 'application/json')
    // Default: true
    MinifyJSON bool

    // MinifyXML: Enable for XML content types
    // (e.g., 'application/xml', 'text/xml')
    // Default: true
    MinifyXML bool

    // MinifySVG: Enable for 'image/svg+xml'
    // Default: true
    MinifySVG bool
}

🔧 Default Configuration

When calling minify.New() without arguments:

// ConfigDefault is the default config
var ConfigDefault = Config{
    Next:             nil,
    SuppressWarnings: false,
    MinifyHTML:       true,
    MinifyCSS:        true,
    MinifyJS:         true,
    MinifyJSON:       false, // Note: JSON is false by default
    MinifyXML:        false, // Note: XML is false by default
    MinifySVG:        false, // Note: SVG is false by default
}

🤝 Contributing

Contributions are always welcome! Fork the repository, create a feature branch, and submit a Pull Request.

📜 License

This package is licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ConfigDefault = Config{
	Next:                 nil,
	SuppressWarnings:     false,
	MinifyHTML:           true,
	MinifyCSS:            true,
	MinifyJS:             true,
	MinifyJSON:           false,
	MinifyXML:            false,
	MinifySVG:            false,
	HTMLKeepDocumentTags: true,
	HTMLKeepEndTags:      true,
	HTMLKeepQuotes:       false,
	HTMLKeepWhitespace:   false,
	JSPrecision:          0,
	CSSPrecision:         0,
	SVGPrecision:         0,
}

ConfigDefault is the default config

Functions

func New

func New(config ...Config) fiber.Handler

New creates a new middleware handler

Types

type Config

type Config struct {
	// Optional. Default: nil
	Next func(c *fiber.Ctx) bool

	// Optional. Default: false
	SuppressWarnings bool

	MinifyHTML bool
	MinifyCSS  bool
	MinifyJS   bool
	MinifyJSON bool
	MinifyXML  bool
	MinifySVG  bool

	// HTML minifier options
	HTMLKeepDocumentTags bool
	HTMLKeepEndTags      bool
	HTMLKeepQuotes       bool
	HTMLKeepWhitespace   bool

	// JS minifier options
	JSPrecision int

	// CSS minifier options
	CSSPrecision int

	// SVG minifier options
	SVGPrecision int
}

Config defines the config for middleware.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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