Documentation ¶
Index ¶
- Constants
- Variables
- func Fingerprint(r *http.Request, salt string) string
- func GetGeoLite2(path, licenseKey string) error
- func GetScreenClass(width int) string
- func IgnoreHit(r *http.Request) bool
- func Migrate(connection string) error
- func RunAtMidnight(f func()) context.CancelFunc
- func Today() time.Time
- type Analyzer
- func (analyzer *Analyzer) ActiveVisitors(filter *Filter, duration time.Duration) ([]Stats, int, error)
- func (analyzer *Analyzer) AvgSessionDuration(filter *Filter) ([]Stats, error)
- func (analyzer *Analyzer) AvgTimeOnPage(filter *Filter) ([]Stats, error)
- func (analyzer *Analyzer) Browser(filter *Filter) ([]Stats, error)
- func (analyzer *Analyzer) Countries(filter *Filter) ([]Stats, error)
- func (analyzer *Analyzer) Growth(filter *Filter) (*Growth, error)
- func (analyzer *Analyzer) Languages(filter *Filter) ([]Stats, error)
- func (analyzer *Analyzer) OS(filter *Filter) ([]Stats, error)
- func (analyzer *Analyzer) Pages(filter *Filter) ([]Stats, error)
- func (analyzer *Analyzer) Platform(filter *Filter) (*Stats, error)
- func (analyzer *Analyzer) Referrer(filter *Filter) ([]Stats, error)
- func (analyzer *Analyzer) ScreenClass(filter *Filter) ([]Stats, error)
- func (analyzer *Analyzer) TotalSessionDuration(filter *Filter) (int, error)
- func (analyzer *Analyzer) TotalTimeOnPage(filter *Filter) (int, error)
- func (analyzer *Analyzer) VisitorHours(filter *Filter) ([]Stats, error)
- func (analyzer *Analyzer) Visitors(filter *Filter) ([]Stats, error)
- type Client
- func (client *Client) Count(query string, args ...interface{}) (int, error)
- func (client *Client) Get(query string, args ...interface{}) (*Stats, error)
- func (client *Client) SaveHits(hits []Hit) error
- func (client *Client) Select(query string, args ...interface{}) ([]Stats, error)
- func (client *Client) Session(clientID int64, fingerprint string, maxAge time.Time) (string, time.Time, time.Time, error)
- type Filter
- type GeoDB
- type GeoDBConfig
- type Growth
- type Hit
- type HitOptions
- type MockClient
- func (client *MockClient) Count(query string, args ...interface{}) (int, error)
- func (client *MockClient) Get(query string, args ...interface{}) (*Stats, error)
- func (client *MockClient) SaveHits(hits []Hit) error
- func (client *MockClient) Select(query string, args ...interface{}) ([]Stats, error)
- func (client *MockClient) Session(clientID int64, fingerprint string, maxAge time.Time) (string, time.Time, time.Time, error)
- type Stats
- type Store
- type Tracker
- type TrackerConfig
- type UserAgent
Constants ¶
const ( // PlatformDesktop filters for everything on desktops. PlatformDesktop = "desktop" // PlatformMobile filters for everything on mobile devices. PlatformMobile = "mobile" // PlatformUnknown filters for everything where the platform is unspecified. PlatformUnknown = "unknown" )
const ( // BrowserChrome represents the Chrome and Chromium browser. BrowserChrome = "Chrome" // BrowserFirefox represents the Firefox browser. BrowserFirefox = "Firefox" // BrowserSafari represents the Safari browser. BrowserSafari = "Safari" // BrowserOpera represents the Opera browser. BrowserOpera = "Opera" // BrowserEdge represents the Edge browser. BrowserEdge = "Edge" // BrowserIE represents the Internet Explorer browser. BrowserIE = "IE" // OSWindows represents the Windows operating system. OSWindows = "Windows" // OSMac represents the Mac operating system. OSMac = "Mac" // OSLinux represents a Linux distribution. OSLinux = "Linux" // OSAndroid represents the Android operating system. OSAndroid = "Android" // OSiOS represents the iOS operating system. OSiOS = "iOS" // OSWindowsMobile represents the Windows Mobile operating system. OSWindowsMobile = "Windows Mobile" )
const (
// GeoLite2Filename is the default filename of the GeoLite2 database.
GeoLite2Filename = "GeoLite2-Country.mmdb"
)
Variables ¶
var (
ErrNoPeriodOrDay = errors.New("no period or day specified")
)
var NullClient = int64(0)
NullClient is a placeholder for no client (0).
var ScreenClasses = []screenClass{
{1440, "XXL"},
{1024, "XL"},
{800, "L"},
{600, "M"},
{415, "S"},
}
ScreenClasses is a list of typical screen sizes used to group resolutions. Everything below is considered "XS" (tiny).
Functions ¶
func Fingerprint ¶
Fingerprint returns a hash for given request and salt. The hash is unique for the visitor.
func GetGeoLite2 ¶
GetGeoLite2 downloads and unpacks the MaxMind GeoLite2 database. The tarball is downloaded and unpacked at the provided path. The directories will created if required. The license key is used for the download and must be provided for a registered account. Please refer to MaxMinds website on how to do that: https://dev.maxmind.com/geoip/geoip2/geolite2/ The database should be updated on a regular basis.
func GetScreenClass ¶
GetScreenClass returns the screen class for given width in pixels.
func IgnoreHit ¶
IgnoreHit returns true, if a hit should be ignored for given request, or false otherwise. The easiest way to track visitors is to use the Tracker.
func Migrate ¶
Migrate runs the database migration for given connection string. This will use the embedded schema migration scripts. You have to set the x-multi-statement to true, or else it will fail to run the queries.
func RunAtMidnight ¶
func RunAtMidnight(f func()) context.CancelFunc
RunAtMidnight calls given function on each day of month on midnight (UTC), unless it is cancelled by calling the cancel function.
Types ¶
type Analyzer ¶
type Analyzer struct {
// contains filtered or unexported fields
}
Analyzer provides an interface to analyze statistics.
func NewAnalyzer ¶
NewAnalyzer returns a new Analyzer for given Store.
func (*Analyzer) ActiveVisitors ¶
func (analyzer *Analyzer) ActiveVisitors(filter *Filter, duration time.Duration) ([]Stats, int, error)
ActiveVisitors returns the active visitors per path and the total number of active visitors for given duration. Use time.Minute*5 for example to get the active visitors for the past 5 minutes.
func (*Analyzer) AvgSessionDuration ¶
AvgSessionDuration returns the average session duration grouped by day.
func (*Analyzer) AvgTimeOnPage ¶
AvgTimeOnPage returns the average time on page grouped by path.
func (*Analyzer) Growth ¶
Growth returns the growth rate for visitor count, session count, bounces, views, and average session duration or average time on page (if path is set). The growth rate is relative to the previous time range or day. The period or day for the filter must be set, else an error is returned.
func (*Analyzer) Pages ¶
Pages returns the visitor count, session count, bounce rate, views, and average time on page grouped by path.
func (*Analyzer) ScreenClass ¶
ScreenClass returns the visitor count grouped byer screen class.
func (*Analyzer) TotalSessionDuration ¶
TotalSessionDuration returns the total session duration in seconds.
func (*Analyzer) TotalTimeOnPage ¶
TotalTimeOnPage returns the total time on page in seconds.
func (*Analyzer) VisitorHours ¶
VisitorHours returns the visitor count grouped by time of day.
type Client ¶
Client is a ClickHouse database client.
func NewClient ¶
NewClient returns a new client for given database connection string. The logger is optional.
type Filter ¶
type Filter struct { // ClientID is the optional. ClientID int64 // From is the start date of the selected period. From time.Time // To is the end date of the selected period. To time.Time // Day is an exact match for the result set ("on this day"). Day time.Time // Start is the start date and time of the selected period. Start time.Time // Path filters for the path. Path string // Language filters for the ISO language code. Language string // Country filters for the ISO country code. Country string // Referrer filters for the referrer. Referrer string // OS filters for the operating system. OS string // OSVersion filters for the operating system version. OSVersion string // Browser filters for the browser. Browser string // BrowserVersion filters for the browser version. BrowserVersion string // Platform filters for the platform (desktop, mobile, unknown). Platform string // ScreenClass filters for the screen class. ScreenClass string // UTMSource filters for the utm_source query parameter. UTMSource string // UTMMedium filters for the utm_medium query parameter. UTMMedium string // UTMCampaign filters for the utm_campaign query parameter. UTMCampaign string // UTMContent filters for the utm_content query parameter. UTMContent string // UTMTerm filters for the utm_term query parameter. UTMTerm string }
Filter are all fields that can be used to filter the result sets.
type GeoDB ¶
type GeoDB struct {
// contains filtered or unexported fields
}
GeoDB maps IPs to their geo location based on MaxMinds GeoLite2 or GeoIP2 database.
func NewGeoDB ¶
func NewGeoDB(config GeoDBConfig) (*GeoDB, error)
NewGeoDB creates a new GeoDB for given database file. The file is loaded into memory, therefore it's not necessary to close the reader (see oschwald/maxminddb-golang documentatio). The database should be updated on a regular basis.
func (*GeoDB) CountryCode ¶
CountryCode looks up the country code for given IP. If the IP is invalid it will return an empty string. The country code is returned in lowercase.
type GeoDBConfig ¶
type GeoDBConfig struct { // File is the path (including the filename) to the GeoLite2 country database file. // See GeoLite2Filename for the required filename. File string // Logger is the log.Logger used for logging. // Note that this will log the IP address and should therefore only be used for debugging. // Set it to nil to disable logging for GeoDB. Logger *log.Logger }
GeoDBConfig is the configuration for the GeoDB.
type Growth ¶
type Growth struct { VisitorsGrowth float64 `json:"visitors_growth"` ViewsGrowth float64 `json:"views_growth"` SessionsGrowth float64 `json:"sessions_growth"` BouncesGrowth float64 `json:"bounces_growth"` TimeSpentGrowth float64 `json:"time_spent_growth"` }
Growth represents the visitors, views, sessions, bounces, and average session duration growth between two time periods.
type Hit ¶
type Hit struct { ClientID int64 `db:"client_id"` Fingerprint string Time time.Time Session sql.NullTime PreviousTimeOnPageSeconds int `db:"previous_time_on_page_seconds"` UserAgent string `db:"user_agent"` Path string URL string Language string CountryCode string `db:"country_code"` Referrer sql.NullString ReferrerName sql.NullString `db:"referrer_name"` ReferrerIcon sql.NullString `db:"referrer_icon"` OS string OSVersion string `db:"os_version"` Browser string BrowserVersion string `db:"browser_version"` Desktop bool Mobile bool ScreenWidth int `db:"screen_width"` ScreenHeight int `db:"screen_height"` ScreenClass string `db:"screen_class"` UTMSource sql.NullString `db:"utm_source"` UTMMedium sql.NullString `db:"utm_medium"` UTMCampaign sql.NullString `db:"utm_campaign"` UTMContent sql.NullString `db:"utm_content"` UTMTerm sql.NullString `db:"utm_term"` }
Hit represents a single data point/page visit and is the central entity of Pirsch.
func HitFromRequest ¶
func HitFromRequest(r *http.Request, salt string, options *HitOptions) Hit
HitFromRequest returns a new Hit for given request, salt and HitOptions. The salt must stay consistent to track visitors across multiple calls. The easiest way to track visitors is to use the Tracker.
type HitOptions ¶
type HitOptions struct { // Client is the database client required to look up sessions. Client Store // ClientID is optionally saved with a hit to split the data between multiple clients. ClientID int64 // SessionMaxAge defines the maximum time a session stays active. // A session is kept active if requests are made within the time frame. // Set to 15 minutes by default. SessionMaxAge time.Duration // URL can be set to manually overwrite the URL stored for this request. // This will also affect the Path, except it is set too. URL string // Path can be set to manually overwrite the path stored for the request. // This will also affect the URL. Path string // Referrer can be set to manually overwrite the referrer from the request. Referrer string // ReferrerDomainBlacklist is used to filter out unwanted referrers from the Referrer header. // This can be used to filter out traffic from your own site or subdomains. // To filter your own domain and subdomains, add your domain to the list and set ReferrerDomainBlacklistIncludesSubdomains to true. // This way the referrer for blog.mypage.com -> mypage.com won't be saved. ReferrerDomainBlacklist []string // ReferrerDomainBlacklistIncludesSubdomains set to true to include all subdomains in the ReferrerDomainBlacklist, // or else subdomains must explicitly be included in the blacklist. // If the blacklist contains domain.com, sub.domain.com and domain.com will be treated as equals. ReferrerDomainBlacklistIncludesSubdomains bool // ScreenWidth sets the screen width to be stored with the hit. ScreenWidth int // ScreenHeight sets the screen height to be stored with the hit. ScreenHeight int // contains filtered or unexported fields }
HitOptions is used to manipulate the data saved on a hit.
func HitOptionsFromRequest ¶
func HitOptionsFromRequest(r *http.Request) *HitOptions
HitOptionsFromRequest returns the HitOptions for given client request. This function can be used to accept hits from pirsch.js. Invalid parameters are ignored and left empty. You might want to add additional checks before calling HitFromRequest afterwards (like for the HitOptions.ClientID).
type MockClient ¶
type MockClient struct { Hits []Hit // contains filtered or unexported fields }
MockClient is a mock Store implementation.
func (*MockClient) Count ¶
func (client *MockClient) Count(query string, args ...interface{}) (int, error)
Count implements the Store interface.
func (*MockClient) Get ¶
func (client *MockClient) Get(query string, args ...interface{}) (*Stats, error)
func (*MockClient) SaveHits ¶
func (client *MockClient) SaveHits(hits []Hit) error
SaveHits implements the Store interface.
type Stats ¶
type Stats struct { Day time.Time `json:"day,omitempty"` Hour int `json:"hour,omitempty"` Path sql.NullString `json:"path,omitempty"` Referrer sql.NullString `json:"referrer,omitempty"` ReferrerName sql.NullString `db:"referrer_name" json:"referrer_name,omitempty"` ReferrerIcon sql.NullString `db:"referrer_icon" json:"referrer_icon,omitempty"` Language sql.NullString `json:"language,omitempty"` CountryCode sql.NullString `db:"country_code" json:"country_code,omitempty"` Browser sql.NullString `json:"browser,omitempty"` OS sql.NullString `json:"os,omitempty"` Views int `json:"views,omitempty"` Visitors int `json:"visitors,omitempty"` Sessions int `json:"sessions,omitempty"` Bounces int `json:"bounces,omitempty"` RelativeViews float64 `db:"relative_views" json:"relative_views,omitempty"` RelativeVisitors float64 `db:"relative_visitors" json:"relative_visitors,omitempty"` BounceRate float64 `db:"bounce_rate" json:"bounce_rate,omitempty"` ScreenWidth int `db:"screen_width" json:"screen_width,omitempty"` ScreenHeight int `db:"screen_height" json:"screen_height,omitempty"` ScreenClass sql.NullString `db:"screen_class" json:"screen_class,omitempty"` PlatformDesktop int `db:"platform_desktop" json:"platform_desktop,omitempty"` PlatformMobile int `db:"platform_mobile" json:"platform_mobile,omitempty"` PlatformUnknown int `db:"platform_unknown" json:"platform_unknown,omitempty"` RelativePlatformDesktop float64 `db:"relative_platform_desktop" json:"relative_platform_desktop,omitempty"` RelativePlatformMobile float64 `db:"relative_platform_mobile" json:"relative_platform_mobile,omitempty"` RelativePlatformUnknown float64 `db:"relative_platform_unknown" json:"relative_platform_unknown,omitempty"` AverageTimeSpentSeconds int `db:"average_time_spent_seconds" json:"average_time_spent_seconds,omitempty"` }
Stats combines statistical data.
type Store ¶
type Store interface { // SaveHits saves new hits. SaveHits([]Hit) error // Session returns the last path, time, and session timestamp for given client, fingerprint, and maximum age. Session(int64, string, time.Time) (string, time.Time, time.Time, error) // Count returns the number of results for given query. Count(string, ...interface{}) (int, error) // Get returns a single result for given query. Get(string, ...interface{}) (*Stats, error) // Select returns the results for given query. Select(string, ...interface{}) ([]Stats, error) }
Store is the database storage interface.
type Tracker ¶
type Tracker struct {
// contains filtered or unexported fields
}
Tracker provides methods to track requests. Make sure you call Stop to make sure the hits get stored before shutting down the server.
func NewTracker ¶
func NewTracker(client Store, salt string, config *TrackerConfig) *Tracker
NewTracker creates a new tracker for given client, salt and config. Pass nil for the config to use the defaults. The salt is mandatory.
func (*Tracker) Flush ¶
func (tracker *Tracker) Flush()
Flush flushes all hits to client that are currently buffered by the workers. Call Tracker.Stop to also save hits that are in the queue.
func (*Tracker) Hit ¶
func (tracker *Tracker) Hit(r *http.Request, options *HitOptions)
Hit stores the given request. The request might be ignored if it meets certain conditions. The HitOptions, if passed, will overwrite the Tracker configuration. It's save (and recommended!) to call this function in its own goroutine.
type TrackerConfig ¶
type TrackerConfig struct { // Worker sets the number of workers that are used to client hits. // Must be greater or equal to 1. Worker int // WorkerBufferSize is the size of the buffer used to client hits. // Must be greater than 0. The hits are stored in batch when the buffer is full. WorkerBufferSize int // WorkerTimeout sets the timeout used to client hits. // This is used to allow the workers to client hits even if the buffer is not full yet. // It's recommended to set this to a few seconds. // If you leave it 0, the default timeout is used, else it is limted to 60 seconds. WorkerTimeout time.Duration // ReferrerDomainBlacklist see HitOptions.ReferrerDomainBlacklist. ReferrerDomainBlacklist []string // ReferrerDomainBlacklistIncludesSubdomains see HitOptions.ReferrerDomainBlacklistIncludesSubdomains. ReferrerDomainBlacklistIncludesSubdomains bool // SessionMaxAge see HitOptions.SessionMaxAge. SessionMaxAge time.Duration // GeoDB enables/disabled mapping IPs to country codes. // Can be set/updated at runtime by calling Tracker.SetGeoDB. GeoDB *GeoDB // Logger is the log.Logger used for logging. // The default log will be used printing to os.Stdout with "pirsch" in its prefix in case it is not set. Logger *log.Logger }
TrackerConfig is the optional configuration for the Tracker.
type UserAgent ¶
type UserAgent struct { // Browser is the browser name. Browser string // BrowserVersion is the browser (non technical) version number. BrowserVersion string // OS is the operating system. OS string // OSVersion is the operating system version number. OSVersion string }
UserAgent contains information extracted from the User-Agent header.
func ParseUserAgent ¶
ParseUserAgent parses given User-Agent header and returns the extracted information. This just supports major browsers and operating systems, we don't care about browsers and OSes that have no market share, unless you prove us wrong.