analytics

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package analytics provides privacy-first website analytics.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CleanReferrer

func CleanReferrer(ref string) string

CleanReferrer extracts the domain from a referrer URL.

func ExtractBotName

func ExtractBotName(ua string) string

ExtractBotName extracts the bot name from User-Agent string.

func GenerateVisitorID

func GenerateVisitorID(ip, userAgent string) string

GenerateVisitorID creates a salted visitor ID from IP and User-Agent.

func HashIP

func HashIP(ip string) string

HashIP creates a salted SHA-256 hash of an IP address.

func InitSalt

func InitSalt(store *Store) error

InitSalt loads or generates a persistent salt for IP hashing. Must be called once at startup before any requests are served.

func IsBot

func IsBot(ua string) bool

IsBot checks if the User-Agent is likely a bot/crawler.

func ParseUserAgent

func ParseUserAgent(ua string) (browser, os, device string)

ParseUserAgent extracts browser, OS, and device from User-Agent string.

func TruncateDate

func TruncateDate(t time.Time, period string) time.Time

TruncateDate returns the date truncated to the specified period.

Types

type BotStats

type BotStats struct {
	Period      string          `json:"period"`
	TotalVisits int             `json:"total_visits"`
	TopBots     []DimensionStat `json:"top_bots"`
	TopPages    []PageStat      `json:"top_pages"`
	DailyVisits []DailyView     `json:"daily_visits"`
}

BotStats holds aggregated bot analytics data.

type BotStatsResponse

type BotStatsResponse struct {
	Stats      *BotStats `json:"stats"`
	PeriodDays int       `json:"period_days"`
	Hourly     bool      `json:"hourly"`
	Monthly    bool      `json:"monthly"`
}

BotStatsResponse is the JSON response for bot stats endpoint.

type BotVisit

type BotVisit struct {
	ID        int64     `json:"-"`
	BotName   string    `json:"bot_name"`   // Name of the bot (e.g., "Googlebot")
	IPHash    string    `json:"-"`          // Hashed IP address
	UserAgent string    `json:"user_agent"` // Full user agent string
	Path      string    `json:"path"`       // Page path
	Timestamp time.Time `json:"timestamp"`
}

BotVisit represents a single bot/crawler page view.

type CollectRequest

type CollectRequest struct {
	Path        string `json:"path"`
	Referrer    string `json:"referrer"`
	ScreenSize  string `json:"screen_size"`
	UserAgent   string `json:"user_agent"`
	DurationSec int    `json:"duration_sec"`
}

CollectRequest is the expected request body for the collect endpoint.

type DailyView

type DailyView struct {
	Date  string `json:"date"`
	Views int    `json:"views"`
}

DailyView represents views per day.

type DimensionStat

type DimensionStat struct {
	Name  string `json:"name"`
	Count int    `json:"count"`
}

DimensionStat represents a dimension breakdown (browser, OS, etc.).

type Handler

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

Handler handles analytics HTTP requests.

func NewHandler

func NewHandler(store *Store) *Handler

NewHandler creates a new analytics handler. The collect endpoint is rate-limited to 60 requests per IP per minute.

func (*Handler) Collect

func (h *Handler) Collect(c echo.Context) error

Collect handles incoming analytics data from clients.

func (*Handler) Dashboard

func (h *Handler) Dashboard(c echo.Context) error

Dashboard renders the analytics dashboard HTML.

func (*Handler) DashboardHTML

func (h *Handler) DashboardHTML(c echo.Context) error

DashboardHTML serves the standalone HTML dashboard using templ.

func (*Handler) GetBotStats

func (h *Handler) GetBotStats(c echo.Context) error

GetBotStats returns bot analytics statistics as JSON.

func (*Handler) GetBotStatsFragment

func (h *Handler) GetBotStatsFragment(c echo.Context) error

GetBotStatsFragment returns HTML fragment for bot stats (htmx)

func (*Handler) GetSetupFragment

func (h *Handler) GetSetupFragment(c echo.Context) error

GetSetupFragment returns HTML fragment for setup tab (htmx)

func (*Handler) GetStats

func (h *Handler) GetStats(c echo.Context) error

GetStats returns analytics statistics as JSON.

func (*Handler) GetStatsFragment

func (h *Handler) GetStatsFragment(c echo.Context) error

GetStatsFragment returns HTML fragment for visitor stats (htmx)

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(e *echo.Echo, publicGroup *echo.Group, authMiddleware echo.MiddlewareFunc)

RegisterRoutes registers analytics routes with the Echo router.

type LatestPageVisit

type LatestPageVisit struct {
	Path      string `json:"path"`
	Timestamp string `json:"timestamp"`
	Browser   string `json:"browser"`
}

LatestPageVisit represents a single recent page visit.

type PageStat

type PageStat struct {
	Path  string `json:"path"`
	Views int    `json:"views"`
}

PageStat represents page view statistics.

type Stats

type Stats struct {
	Period         string            `json:"period"`
	UniqueVisitors int               `json:"unique_visitors"`
	TotalViews     int               `json:"total_views"`
	AvgDuration    int               `json:"avg_duration_sec"`
	TopPages       []PageStat        `json:"top_pages"`
	LatestPages    []LatestPageVisit `json:"latest_pages"`
	BrowserStats   []DimensionStat   `json:"browsers"`
	OSStats        []DimensionStat   `json:"os"`
	DeviceStats    []DimensionStat   `json:"devices"`
	ReferrerStats  []DimensionStat   `json:"referrers"`
	DailyViews     []DailyView       `json:"daily_views"`
}

Stats holds aggregated analytics data.

type StatsResponse

type StatsResponse struct {
	Stats      *Stats `json:"stats"`
	Realtime   int    `json:"realtime_visitors"`
	PeriodDays int    `json:"period_days"`
	Hourly     bool   `json:"hourly"`
	Monthly    bool   `json:"monthly"`
}

StatsResponse is the JSON response for stats endpoint.

type Store

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

Store provides database operations for analytics.

func NewStore

func NewStore(dbPath string) (*Store, error)

NewStore creates a new analytics store.

func (*Store) CleanupOldVisits

func (s *Store) CleanupOldVisits(retentionDays int) error

CleanupOldVisits removes visits and bot visits older than the retention period.

func (*Store) Close

func (s *Store) Close() error

Close closes the database connection.

func (*Store) GetBotStats

func (s *Store) GetBotStats(from, to time.Time, hourly, monthly bool) (*BotStats, error)

GetBotStats returns aggregated bot statistics for the given time period.

func (*Store) GetRealtimeVisitors

func (s *Store) GetRealtimeVisitors() (int, error)

GetRealtimeVisitors returns the number of unique visitors in the last 5 minutes.

func (*Store) GetSetting

func (s *Store) GetSetting(key string) (string, error)

GetSetting retrieves a setting value by key. Returns empty string if not found.

func (*Store) GetStats

func (s *Store) GetStats(from, to time.Time, hourly, monthly bool) (*Stats, error)

GetStats returns aggregated statistics for the given time period.

func (*Store) SaveBotVisit

func (s *Store) SaveBotVisit(bv *BotVisit) error

SaveBotVisit stores a new bot visit in the database.

func (*Store) SaveVisit

func (s *Store) SaveVisit(v *Visit) error

SaveVisit stores a new visit in the database.

func (*Store) SetSetting

func (s *Store) SetSetting(key, value string) error

SetSetting stores a setting value by key (upsert).

func (*Store) StartCleanupScheduler

func (s *Store) StartCleanupScheduler(retentionDays int, interval time.Duration) func()

StartCleanupScheduler runs periodic cleanup of old data. Returns a stop function.

func (*Store) UpdateVisitDuration

func (s *Store) UpdateVisitDuration(visitorID, path string, durationSec int) error

UpdateVisitDuration updates the duration of the most recent visit for a visitor+path.

type Visit

type Visit struct {
	ID          int64     `json:"-"`
	VisitorID   string    `json:"visitor_id"`  // Anonymous fingerprint hash
	SessionID   string    `json:"session_id"`  // Session identifier
	IPHash      string    `json:"-"`           // Hashed IP address
	Browser     string    `json:"browser"`     // Browser name
	OS          string    `json:"os"`          // Operating system
	Device      string    `json:"device"`      // desktop, mobile, tablet
	Path        string    `json:"path"`        // Page path
	Referrer    string    `json:"referrer"`    // Referrer URL
	ScreenSize  string    `json:"screen_size"` // e.g., "1920x1080"
	Timestamp   time.Time `json:"timestamp"`
	DurationSec int       `json:"duration_sec"` // Time spent on page (0 if not available)
}

Visit represents a single page view.

type VisitRequest

type VisitRequest struct {
	Path       string `json:"path"`
	Referrer   string `json:"referrer"`
	ScreenSize string `json:"screen_size"`
	UserAgent  string `json:"user_agent"`
	Language   string `json:"language"`
}

VisitRequest is the data sent from client.

Directories

Path Synopsis
templ: version: v0.3.977
templ: version: v0.3.977

Jump to

Keyboard shortcuts

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