blitzkit

package module
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2025 License: MIT Imports: 30 Imported by: 0

README

BlitzKit: High-Performance Go Web Framework Foundation

Logo

Repository: github.com/r-via/blitzkit

1. Overview

BlitzKit is a high-performance, reusable toolkit for building modern web applications in Go. Leveraging the speed and efficiency of the Fiber v2 web framework, BlitzKit provides a solid foundation by integrating essential features such as an intelligent L1/L2 caching system (in-memory & BadgerDB), optimized static asset processing, structured slog logging, and Prometheus monitoring capabilities.

Designed to be configurable yet "batteries-included" for core infrastructure, BlitzKit handles common web server complexities, allowing developers to focus on business logic and application-specific routing.

Key Features:

  • Fiber v2 Core: Built on the fast and Express.js-inspired Fiber v2 framework.
  • Hybrid L1/L2 Caching:
    • L1 Cache (In-Memory): patrickmn/go-cache for ultra-fast access to frequently used data.
    • L2 Cache (Disk-Persistent): dgraph-io/badger/v4 for persistent caching, complete with background garbage collection (GC).
    • Cache-Aware Rendering: RenderPage (for templ.Component or similar) and RenderBytesPage (for raw byte content like XML, JSON) methods to serve content through the cache.
  • Programmatic Cache Control:
    • Invalidate(key string): Remove specific keys from L1 and L2 caches.
    • Flush(): Clear all data from both L1 and L2 caches (destructive).
  • Cache Warmup:
    • RegisterForPageWarmup and RegisterForBytesWarmup to register content generator functions.
    • ExecuteWarmup to pre-populate L1/L2 caches on application startup, running concurrently.
  • Static Asset Pipeline (StaticProcessor):
    • Automated CSS/JS minification (from SourcesDir) and static file copying (from StaticsDir) to a PublicDir during server initialization.
    • Powered by tdewolff/minify/v2.
    • Prioritizes .debug.js files in development mode for easier debugging.
  • Integrated Observability:
    • Prometheus Metrics: Exposes detailed metrics via /metrics if Config.EnableMetrics is true (uses ansrivas/fiberprometheus/v2). Tracks Fiber requests, cache performance (hits, misses, sets, errors), warmup statistics, and page generation durations.
    • Health Check Endpoint: GET /health endpoint to verify server status and L2 cache (BadgerDB) readability.
  • Structured Logging with slog:
    • Uses Go's standard log/slog for all internal logging.
    • Allows injection of a custom slog.Logger via Config.Logger.
    • Includes a detailed, structured request logging middleware.
  • Centralized Error Handling:
    • A default Fiber ErrorHandler that logs errors and returns appropriate responses (HTML via Config.ErrorComponentGenerator or JSON based on Accept header).
  • Flexible Configuration:
    • Comprehensive Config struct for fine-grained control.
    • Overrides for key settings via standard environment variables (e.g., PORT, CACHE_L1_DEFAULT_TTL).
  • Startup Validation: Rigorous checks for critical directory paths and permissions.
  • Utilities: Helper functions for sitemap XML generation (GenerateSitemapXMLBytes), client IP extraction, default value handling, and more.

2. Getting Started

2.1 Prerequisites
  • Go 1.21 or newer installed.
  • A Go project initialized (go mod init yourproject).
  • (Optional) Templ CLI installed if you are using Templ for HTML generation: go install github.com/a-h/templ/cmd/templ@latest.
2.2 Installation

Install BlitzKit into your project:

go get github.com/r-via/blitzkit@v0.1.4 # Or your desired version
go mod tidy
2.3 Minimal main.go Example

This example demonstrates basic server setup, a cached HTML page, a cached XML sitemap, static file serving, and graceful shutdown.

package main

import (
	"fmt"
	"log/slog"
	"os"
	"os/signal"
	"syscall"
	"time"

	// Assuming you have a 'views' package generated by Templ (or similar)
	"yourproject/views" // Replace with your actual views package path

	"github.com/a-h/templ"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/csrf"    // For CSRF protection
	"github.com/gofiber/fiber/v2/middleware/limiter" // For Rate Limiting

	"github.com/r-via/blitzkit" // Import BlitzKit directly
)

// --- Page Generators ---

// HomePageGenerator creates the home page component.
func HomePageGenerator(server *blitzkit.Server, title string) blitzkit.PageGeneratorFunc {
	return func() (templ.Component, int64, error) {
		server.GetLogger().Info("Generating component for home page", "title", title)
		// In a real app, you might fetch data here.
		// For Templ, ensure views.HomePage exists and takes a string.
		return views.HomePage(title), time.Now().Unix(), nil
	}
}

// SitemapGenerator creates the sitemap.xml content.
func SitemapGenerator(server *blitzkit.Server) blitzkit.BytesGeneratorFunc {
	return func() ([]byte, int64, error) {
		server.GetLogger().Info("Generating sitemap.xml")
		now := time.Now()
		entries := []blitzkit.SitemapEntry{ // Assuming SitemapEntry is part of the blitzkit package
			{URL: "https://example.com/", LastMod: &now, ChangeFreq: blitzkit.SitemapChangeFreqDaily, Priority: 1.0},
			{URL: "https://example.com/about", LastMod: &now, ChangeFreq: blitzkit.SitemapChangeFreqMonthly, Priority: 0.8},
			// Add more entries dynamically based on your content
		}
		xmlBytes, err := blitzkit.GenerateSitemapXMLBytes(entries)
		return xmlBytes, now.Unix(), err
	}
}

// ErrorPageGenerator creates a custom error page component.
func CustomErrorComponentGenerator(isDevMode bool) blitzkit.ErrorComponentGenerator {
	return func(err error, code int, isDev bool) templ.Component {
		errMsg := "An unexpected error occurred."
		if fe, ok := err.(*fiber.Error); ok {
			errMsg = fe.Message
		} else if isDevMode { // Only show detailed error in dev mode
			errMsg = err.Error()
		}

		if !isDevMode && code >= 500 {
			errMsg = "Internal Server Error. Please try again later."
		}
		// Ensure views.ErrorPage exists and takes these parameters.
		return views.ErrorPage(fmt.Sprintf("Error %d", code), errMsg, isDev)
	}
}

// --- HTTP Handlers (using Fiber's standard signature) ---

// homeHandler serves the home page using BlitzKit's cached rendering.
func homeHandler(server *blitzkit.Server) fiber.Handler {
	return func(c *fiber.Ctx) error {
		cacheKey := "home"
		// Use a default TTL from config (IsInfinite: false)
		return server.RenderPage(c, cacheKey, blitzkit.CacheTTLInfo{IsInfinite: false},
			HomePageGenerator(server, "Welcome to BlitzKit!"))
	}
}

// sitemapHandler serves the sitemap.xml using BlitzKit's cached byte rendering.
func sitemapHandler(server *blitzkit.Server) fiber.Handler {
	return func(c *fiber.Ctx) error {
		cacheKey := "sitemap.xml"
		contentType := fiber.MIMEApplicationXMLCharsetUTF8 // Use Fiber's constants
		// Sitemap changes infrequently, good candidate for effectively infinite cache
		return server.RenderBytesPage(c, cacheKey, contentType, blitzkit.CacheTTLInfo{IsInfinite: true},
			SitemapGenerator(server))
	}
}

// adminInvalidateCacheHandler (example for programmatic cache invalidation)
// IMPORTANT: This endpoint MUST be secured in a real application (e.g., auth middleware).
func adminInvalidateCacheHandler(server *blitzkit.Server) fiber.Handler {
	return func(c *fiber.Ctx) error {
		keyToInvalidate := c.Query("key")
		if keyToInvalidate == "" {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Missing 'key' query parameter"})
		}

		if err := server.Invalidate(keyToInvalidate); err != nil {
			server.GetLogger().Error("Failed to invalidate cache", "key", keyToInvalidate, "error", err)
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Cache invalidation failed"})
		}
		server.GetLogger().Info("Cache invalidated successfully", "key", keyToInvalidate)
		return c.JSON(fiber.Map{"message": fmt.Sprintf("Cache key '%s' invalidated", keyToInvalidate)})
	}
}

// notFoundHandler serves a custom 404 page.
func notFoundHandler(server *blitzkit.Server) fiber.Handler {
	return func(c *fiber.Ctx) error {
		// The default ErrorHandler in BlitzKit will try to use ErrorComponentGenerator
		// if the error is a fiber.Error with status 404.
		// So, we just need to return the fiber.ErrNotFound.
		return fiber.ErrNotFound // This will be caught by server.handleError
	}
}

func main() {
	// --- 1. Logger Setup ---
	isDev := os.Getenv("APP_ENV") == "development"
	logLevel := slog.LevelInfo
	if isDev {
		logLevel = slog.LevelDebug
	}
	logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
		Level:     logLevel,
		AddSource: isDev, // Adds source file:line in dev logs
	}))
	slog.SetDefault(logger) // Optional: set as global default logger

	// --- 2. Configuration ---
	cfg := blitzkit.Config{
		Port:              blitzkit.GetEnvOrDefault(logger, "PORT", "", "8080"),
		DevMode:           isDev,
		Logger:            logger, // Inject our configured logger
		SourcesDir:        "./webroot/sources",   // CSS/JS source files for minification
		StaticsDir:        "./webroot/statics",   // Static assets like images, fonts
		PublicDir:         "./webroot/public",    // Output directory for processed & served assets
		CacheDir:          "./runtime/cache",     // Directory for L2 BadgerDB cache
		ReadTimeout:       30 * time.Second,
		WriteTimeout:      30 * time.Second,
		IdleTimeout:       60 * time.Second,
		EnableMetrics:     true, // Enable /metrics endpoint
		CacheL1DefaultTTL: 10 * time.Minute,
		CacheL2DefaultTTL: 24 * time.Hour,
		BadgerGCInterval:  1 * time.Hour,
		WarmupConcurrency: 4,      // Max goroutines for cache warmup
		SecurityHeaders: map[string]string{ // Basic security headers
			"X-Frame-Options":           "DENY",
			"X-Content-Type-Options":    "nosniff",
			"Referrer-Policy":           "strict-origin-when-cross-origin",
			"Strict-Transport-Security": "max-age=31536000; includeSubDomains", // Use HSTS with caution!
			// "Content-Security-Policy": "default-src 'self';", // Example CSP (adapt carefully!)
		},
		// CSRF Configuration (used if you enable the CSRF middleware)
		EnableCSRF:         true, // Flag to indicate intent; middleware must be added manually
		CSRFKeyLookup:      "header:X-CSRF-Token, form:_csrf",
		CSRFCookieName:     "__Host-csrf", // Use __Host- prefix for security if served over HTTPS
		CSRFExpiration:     12 * time.Hour,
		CSRFCookieSameSite: "Lax", // Or "Strict"
		// Rate Limiter Configuration (used if you enable the Limiter middleware)
		EnableRateLimiter:     true, // Flag to indicate intent
		RateLimiterMax:        100,  // Max requests per window per IP
		RateLimiterExpiration: 1 * time.Minute,
		// Custom Error Page Renderer
		ErrorComponentGenerator: CustomErrorComponentGenerator(isDev),
	}

	// --- 3. Server Initialization ---
	server, err := blitzkit.NewServer(cfg)
	if err != nil {
		logger.Error("Failed to initialize BlitzKit server", "error", err)
		os.Exit(1)
	}

	app := server.App() // Get the underlying Fiber app instance

	// --- 4. Configure Middlewares (e.g., CSRF, Rate Limiter) ---
	// These are added manually using the configuration from `cfg`.
	// BlitzKit's base middlewares (recover, CORS, request logging, security headers) are already set up.
	if cfg.EnableCSRF {
		app.Use(csrf.New(csrf.Config{
			KeyLookup:      cfg.CSRFKeyLookup,
			CookieName:     cfg.CSRFCookieName,
			CookieSameSite: cfg.CSRFCookieSameSite,
			Expiration:     cfg.CSRFExpiration,
			// Next: func(c *fiber.Ctx) bool {
			//  // Example: skip CSRF for API routes
			// 	return strings.HasPrefix(c.Path(), "/api/")
			// },
			ContextKey: blitzkit.CSRFContextKey, // Makes CSRF token available via c.Locals(blitzkit.CSRFContextKey)
		}))
		logger.Info("CSRF Protection Middleware enabled.")
	}

	if cfg.EnableRateLimiter {
		app.Use(limiter.New(limiter.Config{
			Max:        cfg.RateLimiterMax,
			Expiration: cfg.RateLimiterExpiration,
			KeyGenerator: func(c *fiber.Ctx) string {
				return blitzkit.GetClientIP(c.Get(fiber.HeaderXForwardedFor), c.IP())
			},
			// LimitReached: func(c *fiber.Ctx) error {
			// 	 return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{"error": "Too many requests"})
			// },
		}))
		logger.Info("Rate Limiting Middleware enabled.")
	}

	// --- 5. Define Application Routes ---
	app.Get("/", homeHandler(server))
	app.Get("/sitemap.xml", sitemapHandler(server))

	// Example POST route (CSRF token would be required if CSRF middleware is active)
	app.Post("/form-submit", func(c *fiber.Ctx) error {
		// CSRF middleware (if enabled) handles validation automatically.
		// Your form processing logic here...
		return c.SendString("Form submitted successfully!")
	})

	// Admin/Protected route for cache invalidation (example)
	// In a real app, add authentication/authorization middleware here
	adminRoutes := app.Group("/admin") // Create a group for admin routes
	// adminRoutes.Use(yourAuthMiddleware) // Apply auth middleware
	adminRoutes.Post("/cache/invalidate", adminInvalidateCacheHandler(server))
	adminRoutes.Post("/cache/flush", func(c *fiber.Ctx) error { // Example flush route
		// server.Flush() // Call this carefully!
		return c.SendString("Cache flush endpoint (implement with caution and security)")
	})


	// --- 6. Register Static File Middleware ---
	// This serves files from `cfg.PublicDir`.
	// It's often placed after application routes unless specific prefix overlaps are desired.
	if cfg.PublicDir != "" {
		app.Static("/", cfg.PublicDir, fiber.Static{
			Compress:      true,
			ByteRange:     true, // Enable byte range requests for seeking in media files
			Browse:        false, // Disable directory browsing for security
			CacheDuration: 24 * time.Hour, // Example browser cache duration for static assets
			MaxAge:        int((24 * time.Hour).Seconds()), // For Cache-Control header
		})
		logger.Info("Static file middleware enabled", "serving_from", cfg.PublicDir)
	}

	// --- 7. Cache Warmup (Optional) ---
	// Register items for warmup
	server.RegisterForPageWarmup("home", blitzkit.CacheTTLInfo{IsInfinite: false},
		HomePageGenerator(server, "Welcome! (Warmed Up)"))
	server.RegisterForBytesWarmup("sitemap.xml", blitzkit.CacheTTLInfo{IsInfinite: true},
		SitemapGenerator(server))

	// Execute warmup in a goroutine to avoid blocking server startup
	go func() {
		logger.Info("Starting cache warmup process...")
		if err := server.ExecuteWarmup(); err != nil {
			logger.Error("Cache warmup process failed", "error", err)
		} else {
			logger.Info("Cache warmup process finished successfully.")
		}
	}()

	// --- 8. Register 404 Not Found Handler (Must be the last middleware/handler) ---
	app.Use(notFoundHandler(server))

	// --- 9. Start Server and Handle Graceful Shutdown ---
	go func() {
		logger.Info("Starting BlitzKit server...", "address", fmt.Sprintf(":%s", cfg.Port))
		if err := server.Start(); err != nil {
			// http.ErrServerClosed is expected on graceful shutdown
			if err.Error() != "http: Server closed" {
				logger.Error("Server failed to start or stopped unexpectedly", "error", err)
				// Consider a mechanism to signal the main goroutine to exit if startup fails critically
			}
		}
	}()

	// Wait for interrupt signal to gracefully shut down the server
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit // Block until a signal is received

	logger.Info("Shutdown signal received. Shutting down BlitzKit server gracefully...")

	// Perform server shutdown (closes Fiber app & L2 cache)
	// shutdownTimeout := 30 * time.Second // server.Shutdown() already has an internal timeout
	if err := server.Shutdown(); err != nil {
		logger.Error("Server shutdown failed", "error", err)
		os.Exit(1) // Exit with an error code
	}

	logger.Info("Server shutdown complete.")
}

3. Configuration (blitzkit.Config)

The blitzkit.Config struct allows fine-grained control over the server's behavior.

Field Type Default (in NewServer) Env Var Override Description
Port string "8080" PORT HTTP listening port.
ReadTimeout time.Duration 30s Max duration for reading the entire request.
WriteTimeout time.Duration 30s Max duration for writing the response.
IdleTimeout time.Duration 60s Max duration for an idle keep-alive connection.
DevMode bool false APP_ENV=development Enables development mode (verbose logs, error details, etc.).
Logger *slog.Logger (default slog logger) Custom slog.Logger instance. If nil, a default is created.
PublicDir string "" Required if serving static files. Absolute/relative path to the public directory (after StaticProcessor runs).
CacheDir string "" Absolute/relative path for BadgerDB L2 cache. If empty, L2 is disabled. Must be writable.
SourcesDir string "" Path to CSS/JS source files for minification.
StaticsDir string "" Path to static assets (images, fonts) to be copied directly to PublicDir.
ErrorHandler func(c *fiber.Ctx, err error) error (internal handleError) Custom Fiber error handler. If nil, BlitzKit's default handleError is used.
NotFoundComponent templ.Component nil Templ component for 404 errors (used by default handleError if no ErrorComponentGenerator and error is 404). Not used by a custom 404 handler.
ErrorComponentGenerator ErrorComponentGenerator nil func(err error, code int, isDev bool) templ.Component to generate custom error pages.
CacheL1DefaultTTL time.Duration 5m CACHE_L1_DEFAULT_TTL Default TTL for L1 cache items (if not IsInfinite).
CacheL2DefaultTTL time.Duration 24h CACHE_L2_DEFAULT_TTL Default TTL for L2 cache items (if not IsInfinite). 0 or negative means no TTL-based expiration for Badger.
BadgerGCInterval time.Duration 1h BADGER_GC_INTERVAL Interval for BadgerDB's value log GC. 0 or negative disables periodic GC.
BadgerGCDiscardRatio float64 0.5 Discard ratio for BadgerDB's GC.
WarmupConcurrency int 4 Max number of goroutines for concurrent cache warmup.
EnableCSRF bool false Flag to indicate if CSRF protection should be enabled (user must add the middleware).
CSRFKeyLookup string "" Fiber CSRF KeyLookup string (e.g., "header:X-CSRF-Token, form:_csrf").
CSRFCookieName string "" Name of the CSRF cookie.
CSRFExpiration time.Duration 0 (no default set by BlitzKit) Expiration duration for CSRF tokens.
CSRFCookieSameSite string "" SameSite policy for the CSRF cookie (e.g., "Lax", "Strict").
EnableRateLimiter bool false Flag to indicate if Rate Limiting should be enabled (user must add the middleware).
RateLimiterMax int 0 (no default set by BlitzKit) Max requests per window for the rate limiter.
RateLimiterExpiration time.Duration 0 (no default set by BlitzKit) Time window for the rate limiter.
SecurityHeaders map[string]string nil Map of HTTP security headers to be added to every response by a base middleware.
EnableMetrics bool false Enables the Prometheus metrics endpoint at /metrics.
CustomMiddlewares []fiber.Handler nil Slice of custom fiber.Handler middlewares to be added after base middlewares.

Environment Variables: BlitzKit recognizes these environment variables to override Config defaults (see NewServer and utils.go for parsing logic):

  • PORT
  • APP_ENV (set to "development" for DevMode)
  • CACHE_L1_DEFAULT_TTL (e.g., "15m", "1h")
  • CACHE_L2_DEFAULT_TTL
  • BADGER_GC_INTERVAL
  • CACHE_L1_CLEANUP_INTERVAL (default 10m used by NewCache internally if not overridden)
  • CORS_ALLOW_ORIGINS (comma-separated list, e.g., "http://localhost:3000,https://app.example.com")

4. Core Components & API

4.1 Server Lifecycle
  • blitzkit.NewServer(cfg Config) (*Server, error): Initializes and returns a new *Server instance. This is the primary entry point. It sets up logging, caching, static processing, base middlewares, and monitoring.
  • (*Server) App() *fiber.App: Returns the underlying *fiber.App instance. Use this to register your application routes, specific middlewares, etc.
  • (*Server) Start() error: Starts the Fiber HTTP server. This is a blocking call.
  • (*Server) Shutdown() error: Initiates a graceful shutdown of the Fiber server and closes the L2 cache.
4.2 Caching System

The caching system is a core part of BlitzKit, designed for performance.

  • CacheEntry struct: Defines the structure stored in L1/L2 cache (Data []byte, LastModified int64, ExpiresAt int64).
  • CacheTTLInfo struct: (IsInfinite bool) Specifies if a cache entry should have an "infinite" TTL (no time-based expiration, relying on manual invalidation or L1/L2 eviction policies). If false, CacheL1DefaultTTL and CacheL2DefaultTTL are used.

Rendering with Cache:

  • (*Server) RenderPage(ctx *fiber.Ctx, key string, ttlInfo CacheTTLInfo, generatorFunc PageGeneratorFunc) error
    • Renders HTML content (typically from a templ.Component via the PageGeneratorFunc) using the L1/L2 cache.
    • PageGeneratorFunc: func() (page templ.Component, lastModified int64, err error)
    • Handles cache lookup (L1 -> L2), content generation on miss, and storing in both caches.
    • Sets Content-Type: text/html; charset=utf-8 and X-Cache-Status header.
  • (*Server) RenderBytesPage(ctx *fiber.Ctx, key string, contentType string, ttlInfo CacheTTLInfo, generatorFunc BytesGeneratorFunc) error
    • Similar to RenderPage but for raw []byte content (e.g., XML, JSON).
    • BytesGeneratorFunc: func() (data []byte, lastModified int64, err error)
    • Sets the provided contentType and X-Cache-Status header.

Manual Cache Management:

  • (*Server) Invalidate(key string) error: Removes a specific key from both L1 and L2 caches. Logs the operation and increments Prometheus counters.
  • (*Server) Flush() error: Destructive operation. Clears all items from the L1 cache and drops all data from the L2 BadgerDB store. Use with caution.

Cache Warmup:

  • (*Server) RegisterForPageWarmup(key string, ttlInfo CacheTTLInfo, generator PageGeneratorFunc): Registers a PageGeneratorFunc for cache warmup.
  • (*Server) RegisterForBytesWarmup(key string, ttlInfo CacheTTLInfo, generator BytesGeneratorFunc): Registers a BytesGeneratorFunc for cache warmup.
  • (*Server) ExecuteWarmup() error: Executes the warmup process for all registered items. It generates content (if not already in L1) and stores it in L1 and L2 caches. Runs concurrently based on Config.WarmupConcurrency. Logs progress and errors, updates Prometheus metrics.
4.3 Static Asset Processing (StaticProcessor)

Executed once during NewServer initialization:

  1. Purges Config.PublicDir: Removes the existing public directory and recreates it.
  2. Minifies Sources: Iterates through Config.SourcesDir.
    • Minifies .css and .js files using tdewolff/minify/v2.
    • If Config.DevMode is true, .debug.js files are prioritized over regular .js files for the same base name (e.g., script.debug.js over script.js).
    • Writes minified output to Config.PublicDir, preserving relative subdirectory structure.
  3. Copies Statics: Recursively copies all files and directories from Config.StaticsDir to Config.PublicDir.

Your application should then serve static files from Config.PublicDir using Fiber's app.Static("/", cfg.PublicDir) middleware.

4.4 Error Handling
  • BlitzKit sets up a default error handler (server.handleError) for the Fiber application.
  • It intercepts errors returned by handlers or from c.Next(err).
  • Logic:
    1. Determines HTTP status code (defaults to 500, uses fiber.Error.Code if available).
    2. Logs the error with request details (path, method, IP, original error).
    3. Sets the response status code.
    4. Response Formatting:
      • If blitzkit.WantsJSON(c) is true (client Accept header contains application/json): Sends a JSON response: {"error": "message"}. In DevMode, internal error details might be included.
      • Else, if Config.ErrorComponentGenerator is provided: Attempts to render the templ.Component returned by this generator.
      • Else (fallback): Sends a plain text response: <code>: <message>.
      • In production (!DevMode), 5xx error messages are generic ("Internal Server Error").
  • blitzkit.ErrorComponentGenerator type: func(err error, code int, isDev bool) templ.Component. Allows you to provide a function that generates a templ.Component for displaying error pages.
4.5 Middlewares

Base Middlewares (Applied Automatically by NewServer):

  • Recovery: github.com/gofiber/fiber/v2/middleware/recover. Stack traces enabled in DevMode.
  • CORS: github.com/gofiber/fiber/v2/middleware/cors. Configured using CORS_ALLOW_ORIGINS environment variable. Strict in production regarding * with credentials.
  • Security Headers: A custom middleware applies headers defined in Config.SecurityHeaders.
  • Request Logging: server.logRequests provides structured slog logs for each request (method, path, status, duration, IP, response size, user-agent, request ID, cache status).
  • Custom Middlewares: Any fiber.Handlers provided in Config.CustomMiddlewares are added.

Optional Middlewares (Manual Setup Required by User):

  • CSRF Protection: If Config.EnableCSRF is true, you should add Fiber's CSRF middleware using settings from Config (e.g., CSRFKeyLookup, CSRFCookieName). Use blitzkit.CSRFContextKey ("csrf") as the ContextKey in csrf.Config to make the token accessible via c.Locals(blitzkit.CSRFContextKey).
  • Rate Limiting: If Config.EnableRateLimiter is true, add Fiber's Limiter middleware using settings from Config (e.g., RateLimiterMax, RateLimiterExpiration).
4.6 Monitoring
  • Prometheus Metrics (Config.EnableMetrics: true):
    • Endpoint: /metrics.
    • Uses github.com/ansrivas/fiberprometheus/v2 for Fiber metrics.
    • Custom BlitzKit metrics (see monitoring.go for full list, prefixed with blitzkit_):
      • Cache L1/L2: hits, misses, sets, l1_loaded_from_l2, l2_set_errors.
      • Invalidation: invalidations_total, invalidation_errors_total.
      • Warmup: warmup_skipped_total, warmup_errors_total, warmup_item_duration_seconds (histogram), warmup_total_duration_seconds (gauge).
      • Page Generation: page_generation_duration_seconds (histogram vec, labeled by cache_key).
  • Health Check Endpoint (GET /health):
    • Always enabled.
    • Checks basic server responsiveness.
    • If Config.CacheDir (L2 cache) is configured, performs a quick read check on BadgerDB.
    • Returns JSON: {"status": "ok|error", "l2_cache": "ok|unhealthy|unavailable", "l2_cache_error": "details if unhealthy"}.
    • HTTP Status: 200 OK if all checks pass, 503 Service Unavailable if a critical component (like L2 cache) fails.
4.7 Utilities
  • blitzkit.SitemapEntry struct & blitzkit.GenerateSitemapXMLBytes([]SitemapEntry) ([]byte, error): For creating sitemap.xml content.
  • blitzkit.GetClientIP(xForwardedFor, remoteAddr string) string: Extracts client IP, prioritizing X-Forwarded-For.
  • blitzkit.WantsJSON(c *fiber.Ctx) bool: Checks if the request Accept header prefers JSON.
  • blitzkit.GetEnvOrDefault(logger *slog.Logger, key, configValue, defaultValue string) string: Utility to fetch environment variables with fallbacks.
  • Other helpers in utils.go for directory management (ensureDirExists, checkDirWritable), default values (defaultDuration, defaultInt), and duration parsing (parseDurationEnv).

5. Advanced Usage & Internals

5.1 Cache Workflow (RenderPage / RenderBytesPage)
  1. HTTP Request arrives -> Fiber processes base middlewares.
  2. User-defined middlewares (CSRF, Limiter, etc.) run.
  3. Fiber routes to your application handler.
  4. Handler calls server.RenderPage(...) or server.RenderBytesPage(...).
  5. L1 Cache Lookup:
    • Hit: Content served from L1. X-Cache-Status: HIT-L1. Metrics updated. Request ends.
    • Miss: Proceed to L2. Metrics updated.
  6. L2 Cache Lookup:
    • Hit (Valid & Unmarshaled): Content served from L2. Content is promoted to L1. X-Cache-Status: HIT-L2. Metrics updated. Request ends.
    • Miss / Expired / Unmarshal Error: Proceed to generation. Metrics updated.
  7. Content Generation: The provided PageGeneratorFunc or BytesGeneratorFunc is executed.
    • For PageGeneratorFunc, the templ.Component is rendered to []byte.
    • Duration is measured and recorded (Prometheus metric).
  8. Store in Cache:
    • Generated content is stored in L1 (with L1 TTL or no expiration). Metrics updated.
    • Generated content (as CacheEntry) is marshaled to JSON and stored in L2 (with L2 TTL or no expiration). Metrics updated.
  9. Serve Generated Content: X-Cache-Status: MISS. Request ends.
5.2 BadgerDB L2 Cache GC
  • If Config.BadgerGCInterval is positive, a background goroutine (runBadgerGC) periodically runs L2.RunValueLogGC(Config.BadgerGCDiscardRatio).
  • This helps reclaim disk space in BadgerDB. It stops gracefully on server shutdown.

6. Best Practices

  • Fiber Handlers: Use the standard func(c *fiber.Ctx) error signature for your route handlers.
  • Cache Keys: Use unique, descriptive, and consistent cache keys. Consider namespacing (e.g., "page:/about", "data:user:123").
  • CacheTTLInfo: Use IsInfinite: true for content that rarely changes or is invalidated manually (e.g., sitemaps, global configuration data). Use false (with appropriate CacheL1/L2DefaultTTL) for dynamic content that benefits from temporary caching.
  • Generator Functions: Keep them focused on data fetching and content creation. Log within them if necessary. They should be idempotent if possible.
  • Selective Warmup: Only warmup critical or frequently accessed pages/resources to avoid excessive startup load.
  • Configuration: Prefer environment variables for deployment-specific settings (port, TTLs, secrets). Use the Config struct for application defaults and structural configuration.
  • Middleware Order: Remember that middleware order is crucial in Fiber. Typically, your 404 handler and app.Static middleware should be registered last.
  • Security for Cache Control: If you expose endpoints to trigger server.Invalidate() or server.Flush() (e.g., for admin purposes), these endpoints MUST be strongly secured with authentication and authorization.

7. Troubleshooting

  • "Directory not writable" errors at startup: Check permissions for Config.CacheDir and Config.PublicDir. The server process needs write access.
  • Static Assets Not Found (404):
    • Ensure app.Static("/", cfg.PublicDir) is correctly configured and typically called after specific application routes that might share URL prefixes.
    • Verify the contents of Config.PublicDir after server startup to confirm assets were processed.
    • Check that the requested URL doesn't match any fiber.Static exclusion patterns if you've configured them.
  • Cache Not Invalidating / Stale Content:
    • Verify configured TTLs (CacheL1DefaultTTL, CacheL2DefaultTTL) and the IsInfinite flag used during RenderPage/RenderBytesPage or warmup registration.
    • Check server logs for L2 cache errors (Prometheus metric blitzkit_cache_l2_set_errors_total can also indicate issues).
    • When using server.Invalidate(key), ensure the key exactly matches the one used for caching.
  • CSRF Issues (if manually enabled):
    • Double-check your csrf.Config settings against Config values from BlitzKit.
    • Ensure your frontend is sending the CSRF token correctly (matching CSRFKeyLookup).
    • Use browser developer tools to inspect cookies (CSRFCookieName) and request headers/form data.
  • 503 Errors / Health Check Fails: Check server logs for BadgerDB errors. Ensure Config.CacheDir is accessible and not corrupted.

8. Potential Roadmap / Future Enhancements

  • Automatic cache busting for static assets (e.g., appending content hashes to filenames).
  • More granular cache TTL options (e.g., per-key prefix or as an option to render methods).
  • OpenTelemetry integration for distributed tracing.
  • Allow applications to register custom health checks.
  • Further improvements to StaticProcessor (e.g., option not to purge PublicDir, support for SASS/TypeScript pre-processing).

Documentation

Overview

File: cache.go Description: Gère la mise en cache à deux niveaux (L1 en mémoire, L2 sur disque via BadgerDB).

Inclut l'initialisation, la fermeture, la gestion du cycle de vie (GC)
et l'adaptation du logger BadgerDB à slog.

File: cache_methods.go Description: Contient les méthodes du serveur web pour interagir avec le système de cache.

Inclut le rendu de pages HTML (templ) et de données binaires via le cache,
l'invalidation et le vidage du cache.

File: error_handling.go Description: Defines the centralized error handler for the Fiber application. It intercepts errors, determines the appropriate HTTP status code, logs the error, and returns a formatted response (HTML via Templ component, JSON, or plain text).

File: middleware.go Description: Contains the configuration and registration of base middlewares for the Fiber application, such as Recover, CORS, security headers, and request logging.

File: monitoring.go Description: Gère la configuration et l'exposition des métriques Prometheus

et du point de terminaison de contrôle de santé (/health).

Package blitzkit provides a core server toolkit for building web applications with Go and Fiber.

Package blitzkit provides utility functions and core server components, including static file processing capabilities.

Package blitzkit provides a core server toolkit for building web applications with Go and Fiber.

Package blitzkit provides utility functions and core server components.

Index

Constants

View Source
const CSRFContextKey = "csrf"

CSRFContextKey is the key used for storing/retrieving the CSRF token in Fiber context locals.

View Source
const HeaderCacheStatus = "X-BlitzKit-Cache-Status"

HeaderCacheStatus is the HTTP header name used to indicate cache status (HIT/MISS).

Variables

This section is empty.

Functions

func GetClientIP

func GetClientIP(xForwardedFor, remoteAddr string) string

GetClientIP extracts the client's IP address from request headers. It prioritizes X-Forwarded-For, then uses Fiber's RemoteAddr as a fallback.

func IncCacheInvalidationErrors

func IncCacheInvalidationErrors()

IncCacheInvalidationErrors incrémente le compteur d'erreurs d'invalidation si les métriques sont initialisées.

func IncCacheInvalidations

func IncCacheInvalidations()

IncCacheInvalidations incrémente le compteur d'invalidations réussies si les métriques sont initialisées.

func IncCacheL1Hit

func IncCacheL1Hit()

IncCacheL1Hit incrémente le compteur de succès L1 si les métriques sont initialisées.

func IncCacheL1LoadedFromL2

func IncCacheL1LoadedFromL2()

IncCacheL1LoadedFromL2 incrémente le compteur d'éléments L1 chargés depuis L2 si les métriques sont initialisées.

func IncCacheL1Miss

func IncCacheL1Miss()

IncCacheL1Miss incrémente le compteur d'échecs L1 si les métriques sont initialisées.

func IncCacheL1Set

func IncCacheL1Set()

IncCacheL1Set incrémente le compteur d'éléments définis en L1 si les métriques sont initialisées.

func IncCacheL2Hit

func IncCacheL2Hit()

IncCacheL2Hit incrémente le compteur de succès L2 si les métriques sont initialisées.

func IncCacheL2Miss

func IncCacheL2Miss()

IncCacheL2Miss incrémente le compteur d'échecs L2 si les métriques sont initialisées.

func IncCacheL2Set

func IncCacheL2Set()

IncCacheL2Set incrémente le compteur d'éléments définis en L2 si les métriques sont initialisées.

func IncCacheL2SetErrors

func IncCacheL2SetErrors()

IncCacheL2SetErrors incrémente le compteur d'erreurs de définition L2 si les métriques sont initialisées.

func IncCacheWarmupErrors

func IncCacheWarmupErrors()

IncCacheWarmupErrors incrémente le compteur d'erreurs de préchauffage si les métriques sont initialisées.

func IncCacheWarmupSkipped

func IncCacheWarmupSkipped()

IncCacheWarmupSkipped incrémente le compteur d'éléments sautés lors du préchauffage si les métriques sont initialisées.

func Init

func Init()

Init performs one-time initialization for the blitzkit package.

func ObserveCacheWarmupDuration

func ObserveCacheWarmupDuration(duration float64)

ObserveCacheWarmupDuration enregistre la durée de préchauffage d'un élément individuel si les métriques sont initialisées.

func ObserveCacheWarmupTotalDuration

func ObserveCacheWarmupTotalDuration(duration float64)

ObserveCacheWarmupTotalDuration définit la durée totale du dernier préchauffage si les métriques sont initialisées.

func ObservePageGenerationDuration

func ObservePageGenerationDuration(duration float64, cacheKey string)

ObservePageGenerationDuration enregistre la durée de génération d'une page (cache miss) si les métriques sont initialisées.

func WantsJSON

func WantsJSON(c *fiber.Ctx) bool

WantsJSON checks if the request's Accept header indicates a preference for JSON.

Types

type AppMode added in v0.1.8

type AppMode int

AppMode définit le mode de fonctionnement du serveur BlitzKit.

const (
	// ModeFullstack active toutes les fonctionnalités, y compris le service de fichiers statiques et le rendu de templates.
	// C'est la valeur par défaut pour assurer la compatibilité ascendante.
	ModeFullstack AppMode = iota
	// ModeAPI configure le serveur pour fonctionner comme un backend pur (API REST/JSON).
	ModeAPI
)

type BytesGeneratorFunc

type BytesGeneratorFunc func() (data []byte, lastModified int64, err error)

BytesGeneratorFunc defines a function that generates binary data (e.g., JSON, XML) for caching.

type Cache

type Cache struct {
	L1 *cache.Cache
	L2 *badger.DB
	// contains filtered or unexported fields
}

Cache contient les pointeurs vers les caches L1 (en mémoire) et L2 (BadgerDB), ainsi que les éléments de contrôle pour le garbage collector (GC) de BadgerDB.

func NewCache

func NewCache(
	cacheDir string,
	logger *slog.Logger,
	cleanupInterval time.Duration,
	gcInterval time.Duration,
	discardRatio float64,
) (*Cache, error)

NewCache initialise les systèmes de cache L1 (go-cache) et L2 (BadgerDB). Configure les intervalles de nettoyage/GC et démarre la goroutine GC pour BadgerDB si activée. Retourne une erreur si l'initialisation de BadgerDB échoue.

Args:

cacheDir (string): Le chemin du répertoire pour stocker la base de données BadgerDB (L2). Si vide, L2 est désactivé.
logger (*slog.Logger): Le logger structuré à utiliser.
cleanupInterval (time.Duration): L'intervalle de nettoyage pour le cache L1 (go-cache).
gcInterval (time.Duration): L'intervalle pour exécuter le GC du journal de valeurs de BadgerDB (L2). Si <= 0, le GC périodique est désactivé.
discardRatio (float64): Le ratio pour le GC de BadgerDB (généralement 0.5).

Returns:

(*Cache, error): Une instance de Cache initialisée et une erreur nil, ou nil et une erreur en cas d'échec.

func (*Cache) Close

func (c *Cache) Close(logger *slog.Logger) error

Close arrête proprement la goroutine GC de BadgerDB (si elle existe) et ferme la connexion à la base de données BadgerDB (L2).

Args:

logger (*slog.Logger): Le logger structuré à utiliser.

Returns:

error: Une erreur si la fermeture de BadgerDB échoue, sinon nil.

type CacheEntry

type CacheEntry struct {
	Data         []byte `json:"data"`
	LastModified int64  `json:"last_modified"`
	ExpiresAt    int64  `json:"expires_at"`
}

CacheEntry définit la structure stockée dans le cache L1/L2. Contient les données binaires, l'heure de dernière modification et l'heure d'expiration.

type CacheTTLInfo

type CacheTTLInfo struct {
	IsInfinite bool
}

CacheTTLInfo specifies whether a cache entry should have an infinite time-to-live.

type Config

type Config struct {
	// Mode définit si le serveur doit fonctionner en ModeFullstack ou ModeAPI.
	// La valeur par défaut est ModeFullstack si non spécifié.
	Mode AppMode `json:"mode" yaml:"mode"`

	// AppName is the name of the application, used in Fiber config.
	AppName string `json:"app_name" yaml:"app_name"`
	// Port is the TCP port the server will listen on (e.g., "8080").
	Port string `json:"port" yaml:"port"`
	// ReadTimeout is the maximum duration for reading the entire request.
	ReadTimeout time.Duration `json:"read_timeout" yaml:"read_timeout"`
	// WriteTimeout is the maximum duration for writing the response.
	WriteTimeout time.Duration `json:"write_timeout" yaml:"write_timeout"`
	// IdleTimeout is the maximum duration for a persistent connection.
	IdleTimeout time.Duration `json:"idle_timeout" yaml:"idle_timeout"`
	// DevMode enables development mode features (more verbose logging, no prefork, etc.).
	DevMode bool `json:"dev_mode" yaml:"dev_mode"`
	// Logger is the slog.Logger instance. If nil, a default one is created.
	Logger *slog.Logger `json:"-" yaml:"-"`

	// MinifyCSS controls whether CSS files are minified. Used only in ModeFullstack.
	MinifyCSS bool `json:"minify_css" yaml:"minify_css"`
	// MinifyJS controls whether JavaScript files are minified. Used only in ModeFullstack.
	MinifyJS bool `json:"minify_js" yaml:"minify_js"`
	// UseEsbuildIfAvailable enables using esbuild for JS minification. Used only in ModeFullstack.
	UseEsbuildIfAvailable bool `json:"use_esbuild_if_available" yaml:"use_esbuild_if_available"`
	// PublicDir is the path to the directory for processed static files. Used only in ModeFullstack.
	PublicDir string `json:"public_dir" yaml:"public_dir"`
	// SourcesDir is the path to CSS/JS sources to be minified. Used only in ModeFullstack.
	SourcesDir string `json:"sources_dir" yaml:"sources_dir"`
	// StaticsDir is the path to static files to be copied directly. Used only in ModeFullstack.
	StaticsDir string `json:"statics_dir" yaml:"statics_dir"`
	// ErrorComponentGenerator generates a templ.Component for error pages. Used only in ModeFullstack.
	ErrorComponentGenerator ErrorComponentGenerator `json:"-" yaml:"-"`

	// CacheDir is the path for L2 cache (BadgerDB). If empty, L2 cache is disabled.
	CacheDir string `json:"cache_dir" yaml:"cache_dir"`
	// CacheL1DefaultTTL is the default time-to-live for items in the L1 (memory) cache.
	CacheL1DefaultTTL time.Duration `json:"cache_l1_default_ttl" yaml:"cache_l1_default_ttl"`
	// CacheL2DefaultTTL is the default time-to-live for items in the L2 (BadgerDB) cache.
	CacheL2DefaultTTL time.Duration `json:"cache_l2_default_ttl" yaml:"cache_l2_default_ttl"`
	// BadgerGCInterval is the interval for triggering BadgerDB's Garbage Collector.
	BadgerGCInterval time.Duration `json:"badger_gc_interval" yaml:"badger_gc_interval"`
	// BadgerGCDiscardRatio is the ratio used by BadgerDB's GC (typically 0.5).
	BadgerGCDiscardRatio float64 `json:"badger_gc_discard_ratio" yaml:"badger_gc_discard_ratio"`
	// WarmupConcurrency is the max number of goroutines for concurrent cache warmup.
	WarmupConcurrency int `json:"warmup_concurrency" yaml:"warmup_concurrency"`

	// EnableCSRF enables or disables CSRF protection middleware.
	EnableCSRF bool `json:"enable_csrf" yaml:"enable_csrf"`
	// CSRFKeyLookup specifies where to look for the CSRF token (e.g., "header:X-CSRF-Token").
	CSRFKeyLookup string `json:"csrf_key_lookup" yaml:"csrf_key_lookup"`
	// CSRFCookieName is the name of the cookie storing the CSRF secret.
	CSRFCookieName string `json:"csrf_cookie_name" yaml:"csrf_cookie_name"`
	// CSRFExpiration is the duration for which the CSRF token is valid.
	CSRFExpiration time.Duration `json:"csrf_expiration" yaml:"csrf_expiration"`
	// CSRFCookieSameSite is the SameSite policy for the CSRF cookie.
	CSRFCookieSameSite string `json:"csrf_cookie_same_site" yaml:"csrf_cookie_same_site"`
	// EnableRateLimiter enables or disables the rate limiting middleware.
	EnableRateLimiter bool `json:"enable_rate_limiter" yaml:"enable_rate_limiter"`
	// RateLimiterMax is the max requests allowed per time window.
	RateLimiterMax int `json:"rate_limiter_max" yaml:"rate_limiter_max"`
	// RateLimiterExpiration is the duration of the time window for rate limiting.
	RateLimiterExpiration time.Duration `json:"rate_limiter_expiration" yaml:"rate_limiter_expiration"`
	// SecurityHeaders is a map of HTTP security headers to add to every response.
	SecurityHeaders map[string]string `json:"security_headers" yaml:"security_headers"`
	// CustomMiddlewares is a slice of custom Fiber middlewares to add to the global chain.
	CustomMiddlewares []fiber.Handler `json:"-" yaml:"-"`

	// EnableMetrics enables or disables exposing Prometheus metrics via /metrics.
	EnableMetrics bool `json:"enable_metrics" yaml:"enable_metrics"`

	// --- Handlers ---
	// ErrorHandler is a custom function to handle Fiber errors. If nil, a default handler is used.
	ErrorHandler func(c *fiber.Ctx, err error) error `json:"-" yaml:"-"`
}

Config holds all configuration parameters for the BlitzKit web server.

type ErrorComponentGenerator

type ErrorComponentGenerator func(err error, code int, isDev bool) templ.Component

ErrorComponentGenerator defines a function that generates a templ.Component to display an error page. Used only in ModeFullstack.

type PageGeneratorFunc

type PageGeneratorFunc func() (page templ.Component, lastModified int64, err error)

PageGeneratorFunc defines a function that generates an HTML page for caching. Used only in ModeFullstack.

type Server

type Server struct {
	Cache *Cache
	// contains filtered or unexported fields
}

Server encapsulates the Fiber application, configuration, logger, cache system, and cache warmup registry.

func NewServer

func NewServer(cfg Config) (*Server, error)

NewServer creates and configures a new web server instance. It validates the configuration based on the selected Mode (API or Fullstack), initializes the logger, cache, Fiber app, and conditionally processes static files.

func (*Server) App

func (s *Server) App() *fiber.App

App returns the underlying Fiber application instance.

func (*Server) ExecuteWarmup

func (s *Server) ExecuteWarmup() error

ExecuteWarmup runs the cache warmup process for all registered items.

func (*Server) Flush

func (s *Server) Flush() error

Flush vide complètement les caches L1 (mémoire) et L2 (disque - BadgerDB DropAll). Cette opération est destructive et supprime toutes les données mises en cache. Logue les informations sur l'opération et les éventuelles erreurs.

Returns:

error: Retourne la première erreur rencontrée lors du vidage L2, ou nil si l'opération réussit.

func (*Server) GetConfig

func (s *Server) GetConfig() Config

GetConfig returns a copy of the server's effective configuration.

func (*Server) GetLogger

func (s *Server) GetLogger() *slog.Logger

GetLogger returns the slog.Logger instance.

func (*Server) Invalidate

func (s *Server) Invalidate(key string) error

Invalidate supprime une clé spécifique des caches L1 et L2. Logue les informations sur l'opération et les éventuelles erreurs de suppression L2. Incrémente les compteurs Prometheus correspondants.

Args:

key (string): La clé de cache à invalider.

Returns:

error: Retourne la première erreur rencontrée lors de la suppression L2, ou nil si l'opération réussit.

func (*Server) RegisterForBytesWarmup

func (s *Server) RegisterForBytesWarmup(key string, ttlInfo CacheTTLInfo, generator BytesGeneratorFunc)

RegisterForBytesWarmup registers a BytesGeneratorFunc for cache warmup (API and Fullstack modes).

func (*Server) RegisterForPageWarmup

func (s *Server) RegisterForPageWarmup(key string, ttlInfo CacheTTLInfo, generator PageGeneratorFunc)

RegisterForPageWarmup registers a PageGeneratorFunc for cache warmup (Fullstack mode).

func (*Server) RenderBytesPage

func (s *Server) RenderBytesPage(ctx interface{}, key string, contentType string, ttlInfo CacheTTLInfo, generatorFunc BytesGeneratorFunc) error

RenderBytesPage effectue le rendu de données binaires (ex: XML, CSS, JS) (générées par une fonction `BytesGeneratorFunc`) en utilisant le système de cache L1/L2. La logique est similaire à `RenderPage`, mais travaille directement avec des slices de bytes. Définit l'en-tête `X-Cache-Status` et le `Content-Type` fourni.

Args:

ctx (interface{}): Le contexte de la requête, attendu comme *fiber.Ctx.
key (string): La clé unique identifiant ces données dans le cache.
contentType (string): Le type MIME à définir dans l'en-tête Content-Type de la réponse.
ttlInfo (CacheTTLInfo): Informations sur la durée de vie du cache (infini ou par défaut).
generatorFunc (BytesGeneratorFunc): La fonction qui génère la slice de bytes et le timestamp lastModified si le cache est manquant.

Returns:

error: Une erreur si le type de contexte est invalide, si la génération échoue,
       ou si l'envoi de la réponse échoue. Gérée par l'ErrorHandler de Fiber.

func (*Server) RenderPage

func (s *Server) RenderPage(ctx interface{}, key string, ttlInfo CacheTTLInfo, generatorFunc PageGeneratorFunc) error

RenderPage effectue le rendu d'une page HTML (générée par une fonction `PageGeneratorFunc`) en utilisant le système de cache L1/L2. 1. Tente de récupérer depuis L1. 2. Si absent ou invalide, tente de récupérer depuis L2. 3. Si L2 trouvé et valide, le charge dans L1 et sert le contenu. 4. Si L2 absent ou expiré, appelle `generatorFunc`, stocke le résultat dans L1 et L2, et sert le contenu généré. Définit l'en-tête `X-Cache-Status` (HIT-L1, HIT-L2, MISS) et `Content-Type`.

Args:

ctx (interface{}): Le contexte de la requête, attendu comme *fiber.Ctx.
key (string): La clé unique identifiant cette page dans le cache.
ttlInfo (CacheTTLInfo): Informations sur la durée de vie du cache (infini ou par défaut).
generatorFunc (PageGeneratorFunc): La fonction qui génère le composant `templ.Component` et le timestamp lastModified si le cache est manquant.

Returns:

error: Une erreur si le type de contexte est invalide, si la génération échoue,
       si le rendu échoue, ou si l'envoi de la réponse échoue. Gérée par l'ErrorHandler de Fiber.

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown gracefully shuts down the server and its components.

func (*Server) Start

func (s *Server) Start() error

Start begins listening for incoming connections.

type StaticProcessor

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

StaticProcessor handles minification and copying of static assets. It reads from sourcesDir (for CSS/JS to minify) and staticsDir (to copy as-is), and writes processed files to publicDir. Minification behavior is controlled by MinifyCSS, MinifyJS, and UseEsbuildIfAvailable settings.

func NewStaticProcessor

func NewStaticProcessor(
	sourcesDir, staticsDir, publicDir string,
	logger *slog.Logger,
	devMode bool,
	confMinifyCSS bool,
	confMinifyJS bool,
	confUseEsbuild bool,
) *StaticProcessor

NewStaticProcessor creates a new instance of StaticProcessor. It initializes the internal minifier for CSS and JS (as a fallback) and detects the presence of esbuild if configured for use. Minification behavior is determined by the passed boolean flags.

func (*StaticProcessor) Process

func (sp *StaticProcessor) Process() error

Process executes the static asset processing pipeline: 1. Purges (deletes and recreates) the public destination directory. 2. Minifies CSS and JS files found in the sources directory, based on configuration. 3. Copies all files and directories from the statics directory. It returns an aggregated error if any steps fail.

type WarmupRegistration

type WarmupRegistration struct {
	Key           string
	GeneratorFunc interface{}
	IsBytes       bool
	TTLInfo       CacheTTLInfo
}

WarmupRegistration holds information for cache warmup.

Directories

Path Synopsis
utils
sitemap
package sitemap fournit les structures et les outils pour générer des sitemaps XML conformes.
package sitemap fournit les structures et les outils pour générer des sitemaps XML conformes.

Jump to

Keyboard shortcuts

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