analytics

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 23 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 normalizes raw URLs and historical stored labels to one source.

func ExtractBotName

func ExtractBotName(ua string) string

ExtractBotName extracts the bot name from User-Agent string.

func InitSalt

func InitSalt(store *Store) error

InitSalt initializes this store's persistent hashing key. Failed attempts can retry. NewStore calls it before returning; repeated calls on that store are harmless.

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 {
	PageViewID string    `json:"page_view_id"`
	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 {
	Event       string `json:"event"`
	PageViewID  string `json:"page_view_id"`
	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) Close added in v0.4.0

func (h *Handler) Close()

Close stops the handler's background rate-limiter worker.

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 (talkdom)

func (*Handler) GetSetupFragment

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

GetSetupFragment returns HTML fragment for setup tab (talkdom)

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 (talkdom)

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) GenerateVisitorID added in v0.4.0

func (s *Store) GenerateVisitorID(ip, userAgent string) string

GenerateVisitorID creates a persistent installation-scoped visitor identifier.

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) GetBotStatsContext added in v0.4.0

func (s *Store) GetBotStatsContext(ctx context.Context, from, to time.Time, hourly, monthly bool) (*BotStats, error)

func (*Store) GetRealtimeVisitors

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

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

func (*Store) GetRealtimeVisitorsContext added in v0.4.0

func (s *Store) GetRealtimeVisitorsContext(ctx context.Context) (int, error)

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) GetStatsContext added in v0.4.0

func (s *Store) GetStatsContext(ctx context.Context, from, to time.Time, hourly, monthly bool) (*Stats, error)

func (*Store) HashIP added in v0.4.0

func (s *Store) HashIP(ip string) string

HashIP creates a hash scoped to this analytics installation.

func (*Store) SaveBotVisit

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

SaveBotVisit stores a new bot visit in the database.

func (*Store) SaveBotVisitContext added in v0.4.0

func (s *Store) SaveBotVisitContext(ctx context.Context, bv *BotVisit) error

func (*Store) SaveVisit

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

SaveVisit stores a new visit in the database.

func (*Store) SaveVisitContext added in v0.4.0

func (s *Store) SaveVisitContext(ctx context.Context, v *Visit) error

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 latest visit for a path. Deprecated: use SaveVisitContext with a page-view ID.

type Visit

type Visit struct {
	PageViewID  string    `json:"page_view_id"`
	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 legacy client payload. Deprecated: use CollectRequest with a page-view ID.

Directories

Path Synopsis
templ: version: v0.3.1020
templ: version: v0.3.1020

Jump to

Keyboard shortcuts

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