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
- func GetClientIP(xForwardedFor, remoteAddr string) string
- func IncCacheInvalidationErrors()
- func IncCacheInvalidations()
- func IncCacheL1Hit()
- func IncCacheL1LoadedFromL2()
- func IncCacheL1Miss()
- func IncCacheL1Set()
- func IncCacheL2Hit()
- func IncCacheL2Miss()
- func IncCacheL2Set()
- func IncCacheL2SetErrors()
- func IncCacheWarmupErrors()
- func IncCacheWarmupSkipped()
- func Init()
- func ObserveCacheWarmupDuration(duration float64)
- func ObserveCacheWarmupTotalDuration(duration float64)
- func ObservePageGenerationDuration(duration float64, cacheKey string)
- func WantsJSON(c *fiber.Ctx) bool
- type AppMode
- type BytesGeneratorFunc
- type Cache
- type CacheEntry
- type CacheTTLInfo
- type Config
- type ErrorComponentGenerator
- type PageGeneratorFunc
- type Server
- func (s *Server) App() *fiber.App
- func (s *Server) ExecuteWarmup() error
- func (s *Server) Flush() error
- func (s *Server) GetConfig() Config
- func (s *Server) GetLogger() *slog.Logger
- func (s *Server) Invalidate(key string) error
- func (s *Server) RegisterForBytesWarmup(key string, ttlInfo CacheTTLInfo, generator BytesGeneratorFunc)
- func (s *Server) RegisterForPageWarmup(key string, ttlInfo CacheTTLInfo, generator PageGeneratorFunc)
- func (s *Server) RenderBytesPage(ctx interface{}, key string, contentType string, ttlInfo CacheTTLInfo, ...) error
- func (s *Server) RenderPage(ctx interface{}, key string, ttlInfo CacheTTLInfo, ...) error
- func (s *Server) Shutdown() error
- func (s *Server) Start() error
- type StaticProcessor
- type WarmupRegistration
Constants ¶
const CSRFContextKey = "csrf"
CSRFContextKey is the key used for storing/retrieving the CSRF token in Fiber context locals.
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 ¶
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 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 ¶
ObservePageGenerationDuration enregistre la durée de génération d'une page (cache miss) si les métriques sont initialisées.
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 ¶
BytesGeneratorFunc defines a function that generates binary data (e.g., JSON, XML) for caching.
type Cache ¶
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.
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 ¶
ErrorComponentGenerator defines a function that generates a templ.Component to display an error page. Used only in ModeFullstack.
type PageGeneratorFunc ¶
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 ¶
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 ¶
ExecuteWarmup runs the cache warmup process for all registered items.
func (*Server) Flush ¶
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) Invalidate ¶
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.
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.