gin

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package gin provides a Gin middleware for automatic website metrics collection (PV, UV, IP, response time, status code, error rate).

The middleware normalizes dynamic route paths to prevent key explosion:

GET /users/123   → /users/:id
GET /posts/456   → /posts/:id
GET /api/v1/items/789 → /api/v1/items/:id

This ensures that each unique route pattern generates only one set of stats keys, regardless of how many different IDs are accessed.

Usage

c := memory.New(
    memory.WithReservoirTimer(4096),
    memory.WithBloomSet(1000000, 0.001),
    memory.WithTTL(memory.TTLConfig{
        RetentionDays: 7,
        OnExpire:      sqliteStore.OnExpire,
    }),
)
wm := stats.NewWebsiteMetrics(c)

r := gin.New()
r.Use(ginstats.Middleware(wm, ginstats.Config{
    GetUserID: func(c *gin.Context) string {
        // Extract user ID from JWT, cookie, header, etc.
        return c.GetString("userID")
    },
}))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Middleware

func Middleware(wm *stats.WebsiteMetrics, cfg Config) gin.HandlerFunc

Middleware returns a Gin middleware that records PV, UV, IP, response time, and error rate for every request.

Keys generated:

pv:<date>:<normalized-path>          — Counter
pv_total:<date>                      — Counter (all paths combined)
uv:<date>                            — HLL (if GetUserID is set)
ip:<date>                            — HLL
vv:<date>                            — Counter (session/visit)
requests:<date>                      — Counter
errors:<date>                        — Counter (if status >= 500)
response_time:<date>                 — Timer (response latency)
bounce:<date>                        — Counter (if single-page visit — tracked via session)
session_duration:<date>              — Timer (session duration — if session tracking enabled)

func NormalizePath

func NormalizePath(path string) string

NormalizePath converts dynamic route paths to parameterized patterns to prevent key explosion in stats.

Examples:

/users/123              → /users/:id
/users/abc              → /users/:id
/api/v1/posts/789       → /api/v1/posts/:id
/api/v1/posts/789/edit  → /api/v1/posts/:id/edit
/files/550e8400-e29b... → /files/:id
/static/css/main.a1b2.css → /static/css/main.css (hash stripped)
/health                 → /health (unchanged)
/                       → / (unchanged)

Rules:

  1. Numeric segments → :id
  2. UUID-like segments (8-4-4-4-12 hex) → :id
  3. Long alphanumeric segments (>10 chars, mixed) → :id
  4. File hashes (name.hash.ext) → name.ext
  5. Query strings are ignored (Gin already strips them from path)

Types

type Config

type Config struct {
	// GetUserID extracts the user ID from the request context.
	// If nil, UV is not recorded (only PV and IP).
	// Return empty string to skip UV for this request.
	GetUserID func(c *gin.Context) string

	// SkipPaths are paths to skip (e.g. "/health", "/metrics").
	// Matching is exact prefix match.
	SkipPaths []string

	// SkipIf returns true to skip stats for this request.
	// If nil, all requests are recorded (except SkipPaths).
	SkipIf func(c *gin.Context) bool

	// PathNormalizer customizes path normalization.
	// If nil, the default normalizer is used (converts dynamic segments to :id).
	PathNormalizer func(path string) string
}

Config configures the stats middleware.

Jump to

Keyboard shortcuts

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