gonify

package module
v3.0.0-beta Latest Latest
Warning

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

Go to latest
Published: May 6, 2025 License: MIT Imports: 14 Imported by: 1

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)
		return c.SendString("<html><body><h1>Hello, Minified World!</h1></body></html>")
	})

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

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

	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 {
			return strings.HasPrefix(c.Path(), "/api/raw/")
		},
	}))

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

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

    app.Get("/api/raw/data", func(c *fiber.Ctx) error {
        c.Set(fiber.HeaderContentType, fiber.MIMEApplicationJSON)
        return c.SendString(`{ "raw": true,    "spacing": "preserved" }`)
    })

	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
    // Default: true
    MinifyJS bool

    // MinifyJSON: Enable for JSON content types
    // Default: true
    MinifyJSON bool

    // MinifyXML: Enable for XML content types
    // 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,
	MinifyXML:        false,
	MinifySVG:        false,
}

🤝 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,
}

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
}

Config defines the config for middleware.

Jump to

Keyboard shortcuts

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