statsstore

package module
v1.35.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: AGPL-3.0 Imports: 26 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Stats Store

Tests Status Go Report Card PkgGoDev

Stats Store - a visitor stats storage implementation for Go.

See github.com/dracory/statsadmin for a complete example of how the store can be used.

License

This project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0). You can find a copy of the license at https://www.gnu.org/licenses/agpl-3.0.en.html

For commercial use, please use my contact page to obtain a commercial license.

Installation

go get -u github.com/dracory/statsstore

Setup

store, err := NewStore(NewStoreOptions{
	VisitorTableName:     "stats_visitor",
	DB:                 databaseInstance,
	AutomigrateEnabled: true,
})

Geo-IP Enrichment

Visitor records are saved with an empty country field by default. To populate country codes (ISO 3166-1 alpha-2), configure a GeoIPResolver and call VisitorEnhance from a background task on your preferred schedule (e.g. every 5 minutes).

Setup
store, err := NewStore(NewStoreOptions{
	VisitorTableName:   "stats_visitor",
	DB:                 databaseInstance,
	AutomigrateEnabled: true,
	GeoIPResolver:      NewDefaultGeoIPResolver(), // uses ip2c.org
	EnhanceBatchSize:   10,                        // records per call (default: 10)
})
Running Enrichment

Call VisitorEnhance from a cron job, task scheduler, or goroutine ticker:

processed, err := store.VisitorEnhance(context.Background())
// processed = number of records that were successfully enriched

VisitorEnhance will:

  1. Fetch up to EnhanceBatchSize visitor records where country is empty
  2. For each record, parse the user agent to fill in browser, OS, device, and device type (if those fields are empty)
  3. Look up the country via the configured GeoIPResolver
  4. Update the record with the enriched data
  5. Return the count of fully processed records (country + UA)

UA fields are updated even if the geo-IP lookup fails, but the country stays empty so the record gets retried on the next call. This makes VisitorEnhance a complete replacement for any custom post-processing task — it handles both UA parsing and country enrichment.

Default Resolver (ip2c.org)

DefaultGeoIPResolver uses the free ip2c.org service. It includes:

  • In-memory cache with 24h TTL — avoids duplicate lookups for the same IP
  • Localhost/private IP detection — returns "UN" (unknown) without making an HTTP call
  • Configurable timeout (default: 5s) and HTTP client (for testing)
resolver := &DefaultGeoIPResolver{
	Endpoint:   "https://ip2c.org/",     // default
	Timeout:    5 * time.Second,         // default
	CacheTTL:   24 * time.Hour,          // default; set to 0 to disable caching
	HTTPClient: myCustomClient,          // optional; nil uses default
}
Custom Resolver

Implement the GeoIPResolver interface to use any geo-IP provider (MaxMind, ipinfo, etc.):

type GeoIPResolver interface {
	Resolve(ctx context.Context, ip string) (string, error)
}
  • Return an ISO2 country code (e.g. "US", "GB") on success
  • Return "" + error on failure (record stays empty for retry)
  • Return "UN" + nil error for unresolvable IPs (localhost, private ranges, etc.)

Example with a local MaxMind database:

type maxmindResolver struct {
	db *geoip2.Reader
}

func (r *maxmindResolver) Resolve(ctx context.Context, ip string) (string, error) {
	addr := net.ParseIP(ip)
	if addr == nil {
		return statsstore.CountryUnknown, nil
	}
	country, err := r.db.Country(addr)
	if err != nil {
		return "", err
	}
	return country.Country.IsoCode, nil
}

store, _ := NewStore(NewStoreOptions{
	// ...
	GeoIPResolver: &maxmindResolver{db: myGeoIPDB},
})

Admin Dashboard

The admin dashboard lives in the standalone github.com/dracory/statsadmin package (extracted from this repo). Embed it by injecting a statsstore.StoreInterface and optional callbacks — a default layout is built in, or supply FuncLayout to wrap the dashboard in your own chrome:

import (
    "github.com/dracory/statsadmin"
    "github.com/dracory/statsstore"
)

handler, err := statsadmin.New(statsadmin.AdminOptions{
    Store:             store,        // required
    FuncLayout:        myFuncLayout, // optional; default layout used when nil
    HomeURL:           "/admin",     // required
    BaseURL:           "/admin/stats", // defaults to "/admin/stats"
    CountryNameByIso2: countryNameByIso2, // optional
    AuthUserID:        func(r *http.Request) string { /* ... */ }, // optional
    FlashError:        func(w, r, msg, url string, delay int) string { /* ... */ }, // optional
})

http.Handle("/admin/stats", handler)
Features
  • Dashboard: Overview with total visitors, unique IPs, top paths/countries/browsers/OS/device types
  • Visitors: Paginated visitor list with filtering (IP, country, browser, OS, device type, path, date range, bot/threat flags)
  • Sessions: Visitor sessions grouped by IP with visit history
  • IP Details: Per-IP deep dive with path history, flag as bot/threat, delete entries
  • Settings: Excluded IP management, bot IP management, automated bot identification scan
  • Vue.js SPA: Each page is a Vue.js single-page app with AJAX data loading
  • No host dependencies: statsadmin depends only on github.com/dracory/statsstore and injected callbacks
Controllers
Controller Query param Description
Dashboard controller=dashboard (default) Overview stats and top-N breakdowns
Visitors controller=visitors Paginated, filterable visitor list
Sessions controller=sessions Sessions grouped by IP
Settings controller=settings Excluded IPs, bot IPs, bot identification
IP Details controller=ip-details&ip=X Per-IP details and actions

See the statsadmin repository for a complete working example and screenshots.

Documentation

Index

Constants

View Source
const (
	COLUMN_ID                   = "id"
	COLUMN_COUNTRY              = "country"
	COLUMN_CREATED_AT           = "created_at"
	COLUMN_SOFT_DELETED_AT      = "soft_deleted_at"
	COLUMN_IP_ADDRESS           = "ip_address"
	COLUMN_PATH                 = "path"
	COLUMN_UPDATED_AT           = "updated_at"
	COLUMN_FINGERPRINT          = "fingerprint"
	COLUMN_USER_AGENT           = "user_agent"
	COLUMN_USER_ACCEPT_LANGUAGE = "user_accept_language"
	COLUMN_USER_ACCEPT_ENCODING = "user_accept_encoding"
	COLUMN_USER_BROWSER         = "user_browser"
	COLUMN_USER_BROWSER_VERSION = "user_browser_version"
	COLUMN_USER_DEVICE          = "user_device"
	COLUMN_USER_DEVICE_TYPE     = "user_device_type"
	COLUMN_USER_OS              = "user_os"
	COLUMN_USER_OS_VERSION      = "user_os_version"
	COLUMN_USER_REFERRER        = "user_referrer"
	COLUMN_BOT                  = "bot"
	COLUMN_THREAT               = "threat"
	COLUMN_SESSION_ID           = "session_id"
	COLUMN_UTM_SOURCE           = "utm_source"
	COLUMN_UTM_MEDIUM           = "utm_medium"
	COLUMN_UTM_CAMPAIGN         = "utm_campaign"
	COLUMN_UTM_TERM             = "utm_term"
	COLUMN_UTM_CONTENT          = "utm_content"
	COLUMN_REFERRER_HOST        = "referrer_host"
)
View Source
const (
	VALUE_YES = "yes"
	VALUE_NO  = "no"
)

Yes/No string values used for boolean-like columns (bot, threat). Stored as VARCHAR(3) to match the existing all-string column convention.

View Source
const (
	COLUMN_KEY             = "key"
	COLUMN_VALUE           = "value"
	SETTING_EXCLUDED_IPS   = "excluded_ips"
	SETTING_EXCLUDED_PATHS = "excluded_paths"
	SETTING_INCLUDED_PATHS = "included_paths"
)

Settings table column names.

View Source
const (
	MAX_LEN_ID                   = 40
	MAX_LEN_PATH                 = 510
	MAX_LEN_FINGERPRINT          = 40
	MAX_LEN_IP_ADDRESS           = 40
	MAX_LEN_COUNTRY              = 2
	MAX_LEN_USER_ACCEPT_LANGUAGE = 100
	MAX_LEN_USER_ACCEPT_ENCODING = 40
	MAX_LEN_USER_AGENT           = 510
	MAX_LEN_USER_OS              = 50
	MAX_LEN_USER_OS_VERSION      = 50
	MAX_LEN_USER_DEVICE          = 100
	MAX_LEN_USER_DEVICE_TYPE     = 50
	MAX_LEN_USER_BROWSER         = 100
	MAX_LEN_USER_BROWSER_VERSION = 100
	MAX_LEN_USER_REFERRER        = 510
	MAX_LEN_BOT                  = 3
	MAX_LEN_THREAT               = 3
	MAX_LEN_SESSION_ID           = 40
	MAX_LEN_UTM                  = 255
	MAX_LEN_REFERRER_HOST        = 255
)

Maximum column lengths for string fields.

View Source
const (
	// GeoIPEndpointDefault is the default IP geolocation endpoint (ip2c.org).
	GeoIPEndpointDefault = "https://ip2c.org/"

	// GeoIPTimeoutDefault is the default timeout for IP geolocation lookups.
	GeoIPTimeoutDefault = 5 * time.Second

	// CountryUnknown is used for IPs that cannot be resolved (e.g. localhost).
	CountryUnknown = "UN"

	// GeoIPCacheTTLDefault is the default TTL for the in-memory IP cache.
	GeoIPCacheTTLDefault = 24 * time.Hour
)
View Source
const DEFAULT_SETTINGS_TABLE = "statsstore_settings"

Default table name for key-value settings.

View Source
const MAX_DATETIME = "9999-12-31 23:59:59"

MAX_DATETIME is a far-future datetime used as the default soft-delete sentinel.

View Source
const SESSION_GAP_MINUTES = 30

SESSION_GAP_MINUTES is the maximum gap between consecutive page views that keeps them in the same session. A view arriving more than this many minutes after the fingerprint's previous view starts a new session.

View Source
const VisitorCreateAsyncBufferSizeDefault = 4096

VisitorCreateAsyncBufferSizeDefault bounds the pending-insert queue when VisitorCreateAsyncEnabled is set. Sized so a burst of requests cannot exhaust memory; when full, new visitor rows are dropped rather than blocking the request path on a database write.

Variables

This section is empty.

Functions

func BotPathPatterns added in v1.22.0

func BotPathPatterns() []string

BotPathPatterns returns the list of path substrings for bot-only files (robots.txt, ads.txt, sitemap.xml, etc.).

func IsBot added in v1.8.0

func IsBot(userAgent string) bool

IsBot checks whether a user-agent string belongs to a bot, crawler, or automated tool. An empty user-agent returns false.

func IsBotPath added in v1.22.0

func IsBotPath(path string) bool

IsBotPath reports whether a request path targets a bot-only file.

func IsDataCenterIP added in v1.8.0

func IsDataCenterIP(ip string) bool

IsDataCenterIP checks whether an IP address falls within known data center CIDR ranges.

func IsMaliciousPath added in v1.22.0

func IsMaliciousPath(path string) bool

IsMaliciousPath reports whether a request path targets a universally malicious endpoint.

func IsReferrerSpam added in v1.8.0

func IsReferrerSpam(referrer string) bool

IsReferrerSpam checks whether a referrer URL host matches a known spam domain.

func MaliciousPathPatterns added in v1.22.0

func MaliciousPathPatterns() []string

MaliciousPathPatterns returns the list of path substrings for universally malicious endpoints (.env, .git/, .svn/, .htpasswd, shell.php).

Types

type DefaultGeoIPResolver added in v1.11.0

type DefaultGeoIPResolver struct {
	Endpoint   string        // default: GeoIPEndpointDefault
	Timeout    time.Duration // default: GeoIPTimeoutDefault
	HTTPClient *http.Client  // injectable for testing; if nil, a default client is used
	CacheTTL   time.Duration // default: GeoIPCacheTTLDefault; set to 0 to disable caching
	// contains filtered or unexported fields
}

DefaultGeoIPResolver implements GeoIPResolver using the ip2c.org service. It includes an in-memory cache with TTL to avoid duplicate lookups for the same IP within the cache window.

func NewDefaultGeoIPResolver added in v1.11.0

func NewDefaultGeoIPResolver() *DefaultGeoIPResolver

NewDefaultGeoIPResolver creates a DefaultGeoIPResolver with sensible defaults.

func (*DefaultGeoIPResolver) Resolve added in v1.11.0

func (r *DefaultGeoIPResolver) Resolve(ctx context.Context, ip string) (string, error)

Resolve looks up the country code for the given IP via ip2c.org.

type GeoIPResolver added in v1.11.0

type GeoIPResolver interface {
	// Resolve returns an ISO2 country code (e.g. "US", "GB") for the given IP.
	// If the IP cannot be resolved, it returns CountryUnknown and nil error.
	// If the lookup itself fails (network error, bad response), it returns
	// an empty string and the error so the caller can leave the field empty
	// for a retry.
	Resolve(ctx context.Context, ip string) (string, error)
}

GeoIPResolver resolves an IP address to an ISO 3166-1 alpha-2 country code. Implementations may use an external API, a local MaxMind database, or any other source. A nil/empty result with no error means the IP could not be resolved and the country should be left empty for a later retry.

type NewStoreOptions

type NewStoreOptions struct {
	VisitorTableName     string
	SettingsTableName    string
	DB                   *sql.DB
	AutomigrateEnabled   bool
	DebugEnabled         bool
	BotFilterEnabled     bool // when true, skip bot/threat traffic at ingestion (don't insert). Independent of BotAutoTagEnabled.
	BotAutoTagEnabled    bool // when true, compute and set bot/threat flags on inserted rows. Also auto-computes flags on VisitorCreate/VisitorUpdate.
	ExcludedPathPrefixes []string
	IncludedPathPrefixes []string // when non-empty, acts as a whitelist: only matching paths are tracked
	ExcludedIPs          []string
	GeoIPResolver        GeoIPResolver // optional; enables VisitorEnhance for batch country enrichment
	EnhanceBatchSize     int           // number of records per VisitorEnhance call; default 10

	// TrustedProxies lists CIDR ranges or IPs of reverse proxies whose
	// forwarding headers (X-Forwarded-For, X-Real-IP) may be trusted when
	// resolving the client IP in VisitorRegister. When empty, req.GetIP is
	// used and forwarding headers are trusted unconditionally — only safe
	// when the app runs behind a proxy that sanitizes them.
	TrustedProxies []string

	// FingerprintSalt is an optional secret prepended before hashing the
	// visitor fingerprint (SHA-256 of IP + user agent). It makes stored
	// fingerprints impossible to reverse by dictionary attack on common
	// IP/UA pairs.
	FingerprintSalt string

	// VisitorCreateAsyncEnabled makes VisitorCreate queue the INSERT on a
	// background worker instead of waiting for the database write. Use on
	// request hot paths (per-request visitor tracking) where insert
	// latency must not block the response. Errors are logged, not
	// returned. Call DrainVisitorWrites during shutdown, before closing
	// the underlying database.
	VisitorCreateAsyncEnabled bool

	// VisitorCreateAsyncBufferSize bounds the pending-insert queue.
	// Values <= 0 use VisitorCreateAsyncBufferSizeDefault.
	VisitorCreateAsyncBufferSize int
}

NewStoreOptions defines the options for creating a new stats store.

type SessionInterface added in v1.33.0

type SessionInterface interface {
	GetSessionID() string
	GetFingerprint() string
	GetIpAddress() string
	GetCountry() string
	GetUserDeviceType() string
	GetUserBrowser() string
	GetUserOs() string

	GetStartedAt() string
	GetStartedAtCarbon() *carbon.Carbon
	GetEndedAt() string
	GetEndedAtCarbon() *carbon.Carbon

	// GetDurationSeconds returns ended_at - started_at in seconds.
	GetDurationSeconds() int64

	GetPageViews() int64
	GetBotRows() int64

	GetEntryPath() string
	SetEntryPath(path string) SessionInterface
	GetExitPath() string
	SetExitPath(path string) SessionInterface

	// IsBounce reports whether the session consisted of a single page view.
	IsBounce() bool
}

SessionInterface defines a visitor session: a group of page views sharing a session id (same fingerprint, consecutive views within SESSION_GAP_MINUTES).

type StoreInterface

type StoreInterface interface {
	// MigrateDown drops the stats store tables
	MigrateDown(ctx context.Context, tx ...*sql.Tx) error

	// MigrateUp creates the stats store tables
	MigrateUp(ctx context.Context, tx ...*sql.Tx) error

	EnableDebug(debug bool)
	GetDB() *sql.DB

	SetBotFilterEnabled(enabled bool)
	IsBotFilterEnabled() bool
	SetBotAutoTagEnabled(enabled bool)
	IsBotAutoTagEnabled() bool

	SetExcludedPathPrefixes(prefixes []string)
	GetExcludedPathPrefixes() []string
	SetIncludedPathPrefixes(prefixes []string)
	GetIncludedPathPrefixes() []string

	// ExcludedPathList/Add/Remove manage persisted excluded path prefixes
	// (stored as a JSON array in the settings table under "excluded_paths").
	// Excluded prefixes are skipped by VisitorRegister.
	ExcludedPathList(ctx context.Context) ([]string, error)
	ExcludedPathAdd(ctx context.Context, prefix string) error
	ExcludedPathRemove(ctx context.Context, prefix string) error

	// IncludedPathList/Add/Remove manage persisted included path prefixes
	// (stored under "included_paths"). When non-empty they act as a
	// whitelist: only matching paths are tracked by VisitorRegister.
	IncludedPathList(ctx context.Context) ([]string, error)
	IncludedPathAdd(ctx context.Context, prefix string) error
	IncludedPathRemove(ctx context.Context, prefix string) error

	SetExcludedIPs(ips []string)
	GetExcludedIPs() []string

	ExcludedIPList(ctx context.Context) ([]string, error)
	ExcludedIPAdd(ctx context.Context, ip string) error
	ExcludedIPRemove(ctx context.Context, ip string) error

	// SettingGet retrieves a setting value by key. Returns empty string and
	// nil error if the key does not exist.
	SettingGet(ctx context.Context, key string) (string, error)
	// SettingSet stores a setting value by key, using upsert semantics.
	SettingSet(ctx context.Context, key, value string) error
	// SettingDelete removes a setting by key. No error if the key is absent.
	SettingDelete(ctx context.Context, key string) error
	// SettingHas reports whether a setting key exists.
	SettingHas(ctx context.Context, key string) (bool, error)
	// SettingList returns all settings as a map of key to value.
	// Returns an empty map if the settings table does not exist or is empty.
	SettingList(ctx context.Context) (map[string]string, error)

	VisitorCount(ctx context.Context, query VisitorQueryInterface) (int64, error)
	VisitorCreate(ctx context.Context, user VisitorInterface) error
	// DrainVisitorWrites flushes the async insert queue (when
	// VisitorCreateAsyncEnabled is set) and returns after all pending
	// rows are written. Safe to call when async is disabled.
	DrainVisitorWrites()
	// VisitorDroppedCount returns rows dropped because the async insert
	// queue was full or already drained. Always 0 when async is disabled.
	VisitorDroppedCount() uint64
	VisitorDelete(ctx context.Context, user VisitorInterface) error
	VisitorDeleteByID(ctx context.Context, id string) error
	VisitorDeleteByIP(ctx context.Context, ip string) (int64, error)
	// VisitorDeleteByIDs permanently deletes all visitor records with the
	// given IDs in a single DELETE. Returns the number of deleted rows.
	VisitorDeleteByIDs(ctx context.Context, ids []string) (int64, error)
	VisitorDeleteOlderThan(ctx context.Context, timestamp string) (int64, error)
	// VisitorSetBotByIP sets the bot flag on all visitor records for the
	// given IP in a single UPDATE. Returns the number of updated rows.
	// Valid bot values are VALUE_YES and VALUE_NO.
	VisitorSetBotByIP(ctx context.Context, ip, bot string) (int64, error)
	// VisitorSetThreatByIP sets the threat flag on all visitor records for
	// the given IP in a single UPDATE. Returns the number of updated rows.
	// Valid threat values are VALUE_YES and VALUE_NO.
	VisitorSetThreatByIP(ctx context.Context, ip, threat string) (int64, error)
	VisitorFindByID(ctx context.Context, userID string) (VisitorInterface, error)
	VisitorList(ctx context.Context, query VisitorQueryInterface) ([]VisitorInterface, error)
	VisitorRegister(ctx context.Context, r *http.Request) error
	VisitorSoftDelete(ctx context.Context, user VisitorInterface) error
	VisitorSoftDeleteByID(ctx context.Context, id string) error
	VisitorUpdate(ctx context.Context, user VisitorInterface) error

	// VisitorEnhance enriches visitor records that have an empty country field.
	// It parses the user agent (browser, OS, device type) and looks up the
	// country via the configured GeoIPResolver. UA fields are updated even if
	// the geo-IP lookup fails; the country stays empty for retry.
	// Returns the number of records fully processed (country + UA).
	// Call this from a background task/cron on whatever schedule suits your
	// traffic (e.g. every 5 minutes).
	//
	// If no GeoIPResolver was configured, it returns 0 and an error.
	VisitorEnhance(ctx context.Context) (int, error)

	// SessionList aggregates visitor rows into sessions (same fingerprint,
	// consecutive views within SESSION_GAP_MINUTES). VisitorQuery filters
	// apply to the underlying rows; limit/offset paginate sessions ordered by
	// last activity. Rows predating the session_id column are excluded.
	SessionList(ctx context.Context, query VisitorQueryInterface) ([]SessionInterface, error)
	// SessionCount counts distinct session ids matching the visitor query.
	SessionCount(ctx context.Context, query VisitorQueryInterface) (int64, error)
	// SessionIDBackfill assigns session ids to legacy rows that predate the
	// session_id column, oldest-first so sessions chain across the gap window.
	SessionIDBackfill(ctx context.Context, query VisitorQueryInterface) (int64, error)
}

StoreInterface defines the interface for a stats store.

func NewStore

func NewStore(opts NewStoreOptions) (StoreInterface, error)

NewStore creates a new stats store.

type UserAgentInfo added in v1.16.0

type UserAgentInfo = botdetect.UserAgentInfo

UserAgentInfo holds parsed user-agent data. Alias of botdetect.UserAgentInfo — all name fields are lowercase.

func ParseUserAgent added in v1.16.0

func ParseUserAgent(ua string) UserAgentInfo

ParseUserAgent extracts browser, OS, device, and device-type from a user-agent string. Delegates to botdetect.ParseUserAgent; unknown values are left as empty strings, and bots report DeviceType "bot".

type VisitorInterface

type VisitorInterface interface {
	// Methods
	FingerprintCalculate() string
	IsSoftDeleted() bool

	GetID() string
	SetID(id string) VisitorInterface

	GetPath() string
	SetPath(path string) VisitorInterface

	GetCountry() string
	SetCountry(country string) VisitorInterface

	GetCreatedAt() string
	GetCreatedAtCarbon() *carbon.Carbon
	SetCreatedAt(createdAt string) VisitorInterface

	GetSoftDeletedAt() string
	GetSoftDeletedAtCarbon() *carbon.Carbon
	SetSoftDeletedAt(deletedAt string) VisitorInterface

	GetFingerprint() string
	SetFingerprint(fingerprint string) VisitorInterface

	GetSessionID() string
	SetSessionID(sessionID string) VisitorInterface

	GetUtmSource() string
	SetUtmSource(utmSource string) VisitorInterface

	GetUtmMedium() string
	SetUtmMedium(utmMedium string) VisitorInterface

	GetUtmCampaign() string
	SetUtmCampaign(utmCampaign string) VisitorInterface

	GetUtmTerm() string
	SetUtmTerm(utmTerm string) VisitorInterface

	GetUtmContent() string
	SetUtmContent(utmContent string) VisitorInterface

	GetReferrerHost() string
	SetReferrerHost(referrerHost string) VisitorInterface

	GetIpAddress() string
	SetIpAddress(ipAddress string) VisitorInterface

	GetUpdatedAt() string
	GetUpdatedAtCarbon() *carbon.Carbon
	SetUpdatedAt(updatedAt string) VisitorInterface

	GetUserAcceptLanguage() string
	SetUserAcceptLanguage(userAcceptLanguage string) VisitorInterface

	GetUserAcceptEncoding() string
	SetUserAcceptEncoding(userAcceptEncoding string) VisitorInterface

	GetUserAgent() string
	SetUserAgent(userAgent string) VisitorInterface

	GetUserBrowser() string
	SetUserBrowser(userBrowser string) VisitorInterface

	GetUserBrowserVersion() string
	SetUserBrowserVersion(userBrowserVersion string) VisitorInterface

	GetUserDevice() string
	SetUserDevice(userDevice string) VisitorInterface

	GetUserDeviceType() string
	SetUserDeviceType(userDeviceType string) VisitorInterface

	GetUserOs() string
	SetUserOs(userOs string) VisitorInterface

	GetUserOsVersion() string
	SetUserOsVersion(userOsVersion string) VisitorInterface

	GetUserReferrer() string
	SetUserReferrer(userReferrer string) VisitorInterface

	GetBot() string
	SetBot(bot string) VisitorInterface

	GetThreat() string
	SetThreat(threat string) VisitorInterface
}

VisitorInterface defines the interface for a visitor record.

func NewVisitor

func NewVisitor() VisitorInterface

NewVisitor creates a new visitor.

func NewVisitorFromExistingData

func NewVisitorFromExistingData(data map[string]string) VisitorInterface

NewVisitorFromExistingData creates a new visitor from a raw column map.

type VisitorQueryInterface added in v1.1.0

type VisitorQueryInterface interface {
	Validate() error

	HasCountry() bool
	Country() string
	SetCountry(country string) VisitorQueryInterface

	HasCreatedAtGte() bool
	CreatedAtGte() string
	SetCreatedAtGte(createdAtGte string) VisitorQueryInterface

	HasCreatedAtLte() bool
	CreatedAtLte() string
	SetCreatedAtLte(createdAtLte string) VisitorQueryInterface

	HasDeviceType() bool
	DeviceType() string
	SetDeviceType(deviceType string) VisitorQueryInterface

	HasDistinct() bool
	Distinct() string
	SetDistinct(distinct string) VisitorQueryInterface

	HasID() bool
	ID() string
	SetID(id string) VisitorQueryInterface

	HasIDIn() bool
	IDIn() []string
	SetIDIn(idIn []string) VisitorQueryInterface

	HasIPIn() bool
	IPIn() []string
	SetIPIn(ipIn []string) VisitorQueryInterface

	HasIPNotIn() bool
	IPNotIn() []string
	SetIPNotIn(ipNotIn []string) VisitorQueryInterface

	HasLimit() bool
	Limit() int
	SetLimit(limit int) VisitorQueryInterface

	HasOffset() bool
	Offset() int
	SetOffset(offset int) VisitorQueryInterface

	HasOrderBy() bool
	OrderBy() string
	SetOrderBy(orderBy string) VisitorQueryInterface

	HasPathContains() bool
	PathContains() string
	SetPathContains(pathContains string) VisitorQueryInterface

	HasSessionID() bool
	SessionID() string
	SetSessionID(sessionID string) VisitorQueryInterface

	HasUtmSource() bool
	UtmSource() string
	SetUtmSource(utmSource string) VisitorQueryInterface

	HasUtmMedium() bool
	UtmMedium() string
	SetUtmMedium(utmMedium string) VisitorQueryInterface

	HasUtmCampaign() bool
	UtmCampaign() string
	SetUtmCampaign(utmCampaign string) VisitorQueryInterface

	HasUtmTerm() bool
	UtmTerm() string
	SetUtmTerm(utmTerm string) VisitorQueryInterface

	HasUtmContent() bool
	UtmContent() string
	SetUtmContent(utmContent string) VisitorQueryInterface

	HasReferrerHost() bool
	ReferrerHost() string
	SetReferrerHost(referrerHost string) VisitorQueryInterface

	HasPathExact() bool
	PathExact() string
	SetPathExact(pathExact string) VisitorQueryInterface

	HasSortOrder() bool
	SortOrder() string
	SetSortOrder(sortOrder string) VisitorQueryInterface

	HasSoftDeletedIncluded() bool
	SoftDeletedIncluded() bool
	SetSoftDeletedIncluded(withSoftDeleted bool) VisitorQueryInterface

	HasBot() bool
	Bot() string
	SetBot(bot string) VisitorQueryInterface

	HasThreat() bool
	Threat() string
	SetThreat(threat string) VisitorQueryInterface
}

VisitorQueryInterface defines the interface for visitor query operations.

func NewVisitorQuery added in v1.1.0

func NewVisitorQuery() VisitorQueryInterface

NewVisitorQuery creates a new visitor query.

func VisitorQuery added in v1.1.0

func VisitorQuery() VisitorQueryInterface

VisitorQuery is a shortcut for NewVisitorQuery.

Jump to

Keyboard shortcuts

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