plausible

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2022 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package plausible implements a client/wrapper for the Plausible Analytics API.

It currently supports the Stats API and the Site Provisioning API.

Making a client and site handlers

Start by creating a client to make requests. Then, request handlers to specific sites from the client:

// Create a client with an API token
client := plausible.NewClient("<your_api_token>")

// Get an handler to perform queries for a given site
mysite := client.Site("example.com")

// You can reuse the same client to get handlers for additional sites
myothersite := client.Site("otherexample.com")

// Use 'mysite' and the 'myothersite' handlers to query stats for the sites

Queries - Stats API

You can use the site handlers to perform queries / requests for data. There are four types of queries: current visitor queries, aggregate queries, time series queries and breakdown queries. This queries can be done using the methods on a site handlers called CurrentVisitors, Aggregate, Timeseries and Breakdown respectively. Check the documentation of each one of these methods for query examples.

The current visitors query is the most straight forward one - for a given site return the number of current visitors. Check the method CurrentVisitors for more information and for examples of this query.

An aggregate query reports data for metrics aggregated over a period of time. A query like "the total number of visitors today" fall into this category, where the period is a day (in this case "today") and the metric is the number of visitors. Check the method Aggregate for more information and for examples of this query.

A time series query reports a list of data points over a period of time, where each data point contains data about metrics for that period of time. A query like "the number of visitors and page views for each day in the 7 days before the 1st of February 2021" falls into this category. Check the method Timeseries for more information and for examples of this query.

A breakdown query reports stats for the value of a given property over a period of time. For instance, a query like "over the last 7 days what are the number of visitors and page views for each page of my site" falls into this category. Check the method Breakdown for more information and for examples of this query.

Provisioning API

The provisioning API allows to create new sites on Plausible and to create shared links for those sites. The methods CreateNewSite and SharedLink respectively implement these requests.

However, please note that these methods are using the provisioning API which requires a token with special permissions for the requests to succeed. For more info: https://plausible.io/docs/sites-api

Time periods

When requesting aggregate information to the API, it's only possible to get data for a given period of time, for instance, "the last 7 days", "the last month" or "the current day" are examples of time periods. All time periods are relative to a date. When the date information is missing from a time period, the date is assumed to be "today". It's also possible to specify a time period between two specific dates.

Time periods are represented by the TimePeriod type.

Properties

Each pageview or custom event has some properties associated with it. These properties can be used when querying the API to filter the results.

Properties are represented by the Property type. Properties have a name and value. The name of a property is represented by the PropertyName type. Typically, most users won't need to make custom property names and can just use the constant PropertyName values declared at the top-level of the package like VisitOs or VisitBrowser.

Filters

Filters allow to drill down and segment the data the results refer to. All queries for data accept an optional filter argument.

Filters are represented by the Filter type is consists of a simple list of properties by which you want to filter.

Metrics

Metrics are aggregate information about the data. All queries have the option for you to choose the metrics you want to see included in the results.

There are four metrics currently that you can ask the results for: number of visitors, number of page views, visit duration and bounce rate. These metrics are represented by the Metric type and there are four constants of this type, each one representing one of the four metrics: Visitors, PageViews, BounceRate and VisitDuration.

Time Intervals

Time intervals are used for time series queries to specify the interval of time between two consecutive data points.

A time interval is represented by the TimeInterval type. There are currently two time intervals supported: date and month which are represented with the DateInterval and MonthInterval constants respectively.

A MonthInterval means a month of difference between data points. For instance, if you ask for time series data over the last 6 months with a month interval, this means you will get 6 data points back - 1 for each month.

A DateInterval, depending on the query, means a day or an hour of difference between each data point. For instance, if you ask for time series data over the last 30 days with a date interval, you will get 30 data points back - 1 for each day. However, with a DateInterval, when the period of the time series refers to a day, for instance "today", the data points will actually have 1 hour of interval between them. You can check the Date string field of each data point to know about which date/hour the data refers to.

Stats API: https://plausible.io/docs/stats-api

Site provisioning API: https://plausible.io/docs/sites-api

Concepts: https://plausible.io/docs/stats-api#concepts

Index

Examples

Constants

View Source
const (
	// Visitors represents the number of visitors metric
	Visitors = Metric("visitors")
	// PageViews represents the number of page views metric
	PageViews = Metric("pageviews")
	// BounceRate represents the bounce rate metric
	BounceRate = Metric("bounce_rate")
	// VisitDuration represents the visit duration metric
	VisitDuration = Metric("visit_duration")
	// Visits represents the number of visits/sessions metric
	Visits = Metric("visits")
	// Events represents the number of events (pageviews + custom events) metric
	Events = Metric("events")
)

Metric values:

View Source
const (
	// EventName is the name of the event name property
	EventName = PropertyName("event:name")
	// EventPage is the name of the event page property
	EventPage = PropertyName("event:page")
	// VisitSource is the name of the source property of a visit
	VisitSource = PropertyName("visit:source")
	// VisitReferrer is the name of the referrer property of a visit
	VisitReferrer = PropertyName("visit:referrer")
	// VisitUtmMedium is the name of utm medium property of a visit
	VisitUtmMedium = PropertyName("visit:utm_medium")
	// VisitUtmSource is the name of utm source property of a visit
	VisitUtmSource = PropertyName("visit:utm_source")
	// VisitUtmCampaign is the name of the utm campaign property of a visit
	VisitUtmCampaign = PropertyName("visit:utm_campaign")
	// VisitDevice is the name of the device property of a visit
	VisitDevice = PropertyName("visit:device")
	// VisitBrowser is the name of the browser property of a visit
	VisitBrowser = PropertyName("visit:browser")
	// VisitBrowserVersion is the name of the browser version property of a visit
	VisitBrowserVersion = PropertyName("visit:browser_version")
	// VisitOs is the name of the operating system property of a visit
	VisitOs = PropertyName("visit:os")
	// VisitOsVersion is the name of the operating system version property of a visit
	VisitOsVersion = PropertyName("visit:os_version")
	// VisitCountry is the name of the country property of a visit
	VisitCountry = PropertyName("visit:country")
)

PropertyName values:

View Source
const (
	// DateInterval represents a time interval for a particular day.
	// With this time interval, each data point in the result will refer to a particular day.
	DateInterval = TimeInterval("date")
	// MonthInterval represents a time interval of a particular month.
	// With this time interval, each data point in the result will refer to a particular month.
	MonthInterval = TimeInterval("month")
)
View Source
const DefaultBaseURL = "https://plausible.io/api/v1/"

DefaultBaseURL contains the default base url for the plausible API.

Variables

This section is empty.

Functions

This section is empty.

Types

type AggregateQuery

type AggregateQuery struct {
	// Period to consider for the aggregate query. The result will include results over this period of time.
	// This field is mandatory.
	Period TimePeriod
	// Metrics to be included in the aggregation result.
	// This field is mandatory.
	Metrics Metrics
	// Filters is a filter over properties to narrow down the aggregation results.
	// This field is optional.
	Filters Filter
	// ComparePreviousPeriod tells whether to include a comparison with the previous period in the query result.
	// This field is optional and will default to false.
	ComparePreviousPeriod bool
}

AggregateQuery represents an API query for aggregate information over a period of time for a given list of metrics. In an aggregate query, the Period field and the Metrics field are mandatory, all the others are optional.

func (*AggregateQuery) Validate

func (aq *AggregateQuery) Validate() (ok bool, invalidReason string)

Validate tells whether the query is valid or not. If the query is not valid, a string explaining why the query is not valid will be returned.

type AggregateResult

type AggregateResult struct {
	// BounceRate represents the bounce rate result for the query.
	// Only use this field if you included the BounceRate metric in your query.
	BounceRate float64 `json:"bounce_rate"`
	// BounceRateChange represents the bounce rate change compared to the previous period.
	// Only use this field if you included the BounceRate metric in your query and ComparePreviousPeriod was set to true.
	BounceRateChange float64 `json:"bounce_rate_change"`

	// Pageviews represents the page view result for the query.
	// Only use this field if you included the PageViews metric in your query.
	Pageviews int `json:"pageviews"`
	// PageviewsChange represents change in the number of pageviews compared to the previous period.
	// Only use this field if you included the PageViews metric in your query and ComparePreviousPeriod was set to true.
	PageviewsChange int `json:"pageviews_change"`

	// VisitDuration represents the visit duration result for the query.
	// Only use this field if you included the VisitDuration metric in your query
	VisitDuration float64 `json:"visit_duration"`
	// VisitDurationChange represents the visit duration change compared to the previous period.
	// Only use this field if you included the VisitVisitDuration metric in your query and ComparePreviousPeriod was set to true.
	VisitDurationChange float64 `json:"visit_duration_change"`

	// Visitors represents the number of visitors result for the query.
	// Only use this field if you included the Visitors metric in your query.
	Visitors int `json:"visitors"`
	// VisitorsChange represents the change in the number of visitors compared to the previous period.
	// Only use this field if you included the Visitors metric in your query and ComparePreviousPeriod was set to true.
	VisitorsChange int `json:"visitors_change"`

	// Visits represents the visits result for the query.
	// Only use this field if you included the Visits metric in your query
	Visits int `json:"visits"`
	// VisitsChange represents the visits change compared to the previous period.
	// Only use this field if you included the Visits metric in your query and ComparePreviousPeriod was set to true.
	VisitsChange int `json:"visits_change"`

	// Events represents the events result for the query.
	// Only use this field if you included the Events metric in your query
	Events int `json:"events"`
	// EventsChange represents the events change compared to the previous period.
	// Only use this field if you included the Events metric in your query and ComparePreviousPeriod was set to true.
	EventsChange int `json:"events_change"`
}

AggregateResult represents the result of an aggregate query.

type BreakdownQuery

type BreakdownQuery struct {
	// Property is the property name for which the breakdown result will be about.
	// This field is mandatory.
	Property PropertyName
	// Period is the period of time to consider for the results.
	// This field is mandatory.
	Period TimePeriod
	// Metrics is a list of metrics for which to include in the results.
	// This field is optional.
	Metrics Metrics
	// Limit limits the number of results to be returned.
	// This field is optional.
	Limit int
	// Page indicates the page number for which to fetch the results. Page numbers start at 1.
	// This field is optional.
	Page int
	// Filters is a filter over properties to narrow down the breakdown results.
	// This field is optional.
	Filters Filter
}

BreakdownQuery represents an API query for detailed information about a property over a period of time. In an breakdown query, the Property field and the Period fields are mandatory, all the others are optional.

func (*BreakdownQuery) Validate

func (bq *BreakdownQuery) Validate() (ok bool, invalidReason string)

Validate tells whether the query is valid or not. If the query is not valid, a string explaining why the query is not valid will be returned.

type BreakdownResult

type BreakdownResult []BreakdownResultEntry

BreakdownResult represents a result

type BreakdownResultEntry

type BreakdownResultEntry struct {
	// PropertyResult contains the property value associated with this entry
	PropertyResult
	// MetricsResult contains the metric information associated with this entry
	MetricsResult
}

BreakdownResultEntry represents an entry in a breakdown query result.

type Client

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

Client handles the interaction with the plausible API.

The client must be initialized with a token using either NewClient or NewClientWithBaseURL. It's safe to use this client concurrently.

func NewClient

func NewClient(token string) *Client

NewClient returns a new API client with the given token. Calling this function is the way most users want to use to create and initialize a new client. This function does not make any network requests.

This client will use the API located at https://plausible.io/api/v1/. If you need to use another base URL for the API, create a client using NewClientWithBaseURL instead.

func NewClientWithBaseURL

func NewClientWithBaseURL(token string, baseURL string) *Client

NewClientWithBaseURL creates a new API token with a given token, similarly to NewClient, but also allows the specification of a base URL for the API. This function does not make any network requests.

This allows the specification of an URL for a self-hosted API or another version of the API. The url must be a complete url as it must contain a schema, the domain for the API and the prefix path of the API, e.g. "https://plausible.io/api/v1/". Including a trailing / in the URL is optional.

func (*Client) BaseURL added in v0.2.0

func (c *Client) BaseURL() string

BaseURL returns the base URL this client is using.

func (*Client) CreateNewSite added in v0.2.0

func (c *Client) CreateNewSite(siteRequest CreateSiteRequest) (CreateSiteResult, error)

CreateNewSite creates a new site in Plausible.

Note: This endpoint requires an API token with permissions to use the sites provisioning API. Check https://plausible.io/docs/sites-api for more info

Example
package main

import (
	"fmt"

	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Create a client with an API token
	// Warning: This token must have permissions to the site provisioning API
	client := plausible.NewClient("<your_api_token>")

	newSiteRequest := plausible.CreateSiteRequest{
		Domain:   "mynewsite.com",
		Timezone: "Europe/Lisbon",
	}

	// Note that we call CreateNewSite directly on the client,
	// and not on a site like the majority of requests
	siteResult, err := client.CreateNewSite(newSiteRequest)

	if err != nil {
		// handle error
	}
	fmt.Printf("Domain: %s | Timezone: %s\n", siteResult.Domain, siteResult.Timezone)
}
Output:

func (*Client) Site

func (c *Client) Site(siteID string) *Site

Site returns a site handler for a given site ID. The returned handler can be used to query the API for information and statistics about the site. This function does not make any network requests.

func (*Client) Token added in v0.2.0

func (c *Client) Token() string

Token returns the token this client is using.

type CreateSiteRequest added in v0.2.0

type CreateSiteRequest struct {
	// Domain of the site to create.
	// This field is mandatory.
	Domain string
	// Timezone name according to the IANA database (e.g "Europe/London").
	// This field is optional and will default to "Etc/UTC".
	Timezone string
}

CreateSiteRequest represents a request to create a new site in Plausible.

func (*CreateSiteRequest) Validate added in v0.2.0

func (csr *CreateSiteRequest) Validate() (bool, string)

Validate tells whether the request is valid or not. If the request is not valid, a string explaining why the request is not valid will be returned.

type CreateSiteResult added in v0.2.0

type CreateSiteResult struct {
	// Domain of the created site.
	Domain string `json:"domain"`
	// Timezone of the newly created site.
	Timezone string `json:"timezone"`
}

CreateSiteResult is the result of a request to create a new site.

type Date

type Date struct {
	// Day of month of the date (1-31)
	Day int
	// Month of the date (1-12)
	Month int
	// Year of the date (1-12)
	Year int
}

Date represents the basic information about a date. It represents the information about date returned by some API calls.

func (*Date) String

func (d *Date) String() string

String converts the Date into a human-readable string.

type DateTime

type DateTime struct {
	Date
	Time
}

DateTime contains basic information about a date and a time. It represents the information about date and time returned by some API calls.

This basic information about the date includes the day of month, month, year. The information about the time includes the hour, minute and second. It does not contain any information about timezones.

func (*DateTime) String

func (dt *DateTime) String() string

String converts the DateTime into a human-readable string.

type Filter

type Filter struct {
	// Properties to filter by
	Properties Properties
}

Filter represents an API query filter over properties of the stats data. The filter is a logic AND over all its properties and values. Filters are used when making a request to the API to narrow the information returned.

Example (Example1)
package main

import (
	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Filter by windows users
	plausible.NewFilter().ByVisitOs("Windows")
}
Output:

Example (Example2)
package main

import (
	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Filter by windows users using firefox
	plausible.NewFilter().ByVisitOs("Windows").ByVisitBrowser("Firefox")
}
Output:

Example (Example3)
package main

import (
	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Filter by windows and ubuntu users using firefox
	plausible.NewFilter().ByVisitOs("Windows|Ubuntu").ByVisitBrowser("Firefox")
}
Output:

Example (Example4)
package main

import (
	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// The following are 3 ways to build the same filter

	// Using the builder pattern to chain properties
	_ = plausible.NewFilter().ByVisitOs("Windows").ByVisitBrowser("Firefox")

	// Using NewFilter
	_ = plausible.NewFilter(
		plausible.Property{Name: plausible.VisitOs, Value: "Windows"},
		plausible.Property{Name: plausible.VisitBrowser, Value: "Firefox"},
	)

	// Instantiating a Filter struct directly
	_ = plausible.Filter{
		Properties: plausible.Properties{
			{Name: plausible.VisitOs, Value: "Windows"},
			{Name: plausible.VisitBrowser, Value: "Firefox"},
		}}
}
Output:

func NewFilter

func NewFilter(properties ...Property) Filter

NewFilter creates a new filter with the given properties.

func (Filter) ByCustomProperty

func (f Filter) ByCustomProperty(propertyName string, value string) Filter

ByCustomProperty adds a filter over a custom property to the current filter.

func (Filter) ByEventName

func (f Filter) ByEventName(eventName string) Filter

ByEventName adds a filter over the event name property to the current filter. By default, there's a reserved event "pageviews" that Plausible provides, otherwise the event must be a custom event name.

func (Filter) ByEventPage

func (f Filter) ByEventPage(page string) Filter

ByEventPage adds a filter over the page property to the current filter.

func (Filter) ByVisitBrowser

func (f Filter) ByVisitBrowser(browser string) Filter

ByVisitBrowser adds a filter over the browser property to the current filter. Examples of browser values are "Chrome", "Safari" and "Firefox".

func (Filter) ByVisitBrowserVersion

func (f Filter) ByVisitBrowserVersion(browserVersion string) Filter

ByVisitBrowserVersion adds a filter over the browser version property to the current filter.

func (Filter) ByVisitCountry

func (f Filter) ByVisitCountry(country string) Filter

ByVisitCountry adds a filter over the country property to the current filter. A country value must be a string with the ISO 3166-1 alpha-2 code of the visitor country.

func (Filter) ByVisitDevice

func (f Filter) ByVisitDevice(device string) Filter

ByVisitDevice adds a filter over the device property to the current filter. Possible values for devices are "Desktop", "Laptop", "Tablet" and "Mobile".

func (Filter) ByVisitOs

func (f Filter) ByVisitOs(operatingSystem string) Filter

ByVisitOs adds a filter over the operating system property to the current filter.

func (Filter) ByVisitOsVersion

func (f Filter) ByVisitOsVersion(osVersion string) Filter

ByVisitOsVersion adds a filter over the operating system version property to the current filter.

func (Filter) ByVisitReferrer

func (f Filter) ByVisitReferrer(referrer string) Filter

ByVisitReferrer adds a filter over the referrer property to the current filter. The referrer must the same as an Referer header value, which means an URL without schema, e.g "example.com/about"

func (Filter) ByVisitSource

func (f Filter) ByVisitSource(source string) Filter

ByVisitSource adds a filter over the source property to the current filter. The source values are populated from the query parameter tags (utm_source, source or ref) or by the Referer HTTP header.

func (Filter) ByVisitUtmCampaign

func (f Filter) ByVisitUtmCampaign(utmCampaign string) Filter

ByVisitUtmCampaign adds a filter over the utm campaign property to the current filter. UTM Campaign values come from the utm_campaign query param.

func (Filter) ByVisitUtmMedium

func (f Filter) ByVisitUtmMedium(utmMedium string) Filter

ByVisitUtmMedium adds a filter over the utm medium property to the current filter. UTM Medium values come from the utm_medium query param.

func (Filter) ByVisitUtmSource

func (f Filter) ByVisitUtmSource(utmSource string) Filter

ByVisitUtmSource adds a filter over the utm source property to the current filter. UTM Source values come from the utm_source query param.

func (Filter) Count added in v0.2.0

func (f Filter) Count() int

Count returns the number of properties in the filter

func (Filter) IsEmpty

func (f Filter) IsEmpty() bool

IsEmpty tells if the filter has no properties

type Metric

type Metric string

Metric represents a Plausible metric. Metrics are used as parts of queries to request specific information. Most users won't need to work with this type directly and can just use the metric constant values defined on this package when a Metric value is needed.

type Metrics

type Metrics []Metric

Metrics represents a list of metrics.

Example
package main

import (
	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Visitors and page views metrics
	_ = plausible.Metrics{
		plausible.Visitors,
		plausible.PageViews,
	}
}
Output:

func AllMetrics

func AllMetrics() Metrics

AllMetrics is an utility function that returns all the metrics. This can be used to easily request information about all the metrics when building a query. However, please note that querying all metrics is not allowed in all type of queries.

func (*Metrics) Count

func (m *Metrics) Count() int

Count returns the number of metrics in the list.

func (*Metrics) IsEmpty

func (m *Metrics) IsEmpty() bool

IsEmpty tells whether the list of metrics has any metrics.

type MetricsResult

type MetricsResult struct {
	// BounceRateRaw contains information about the bounce rate.
	// This field must only be used if the query requested the bounce rate metric.
	// Even when the query requests information for the bounce rate metric, some data points can
	// have this field as nil.
	// If you don't care about the nil value, use the BounceRate function to get this value.
	BounceRateRaw *float64 `json:"bounce_rate"`

	// Pageviews contains information about the number of page views.
	// This field must only be used if the query requested the page views metric.
	Pageviews int `json:"pageviews"`

	// VisitDurationRaw contains information about the visit duration.
	// Only use this field if the query requested the visit duration metric.
	// Even when the query requests information for the visit duration metric, some data points can
	// have this field as nil.
	// If you don't care about the nil value, use the VisitDuration function to get this value.
	VisitDurationRaw *float64 `json:"visit_duration"`

	// Visitors contains information about the number of visitors.
	// This field must only be used if the query requested the visitors metric.
	Visitors int `json:"visitors"`

	// Visits contains information about the number of visits per session.
	// This field must only be used if the query requested the visits metric.
	Visits int `json:"visits"`
}

MetricsResult contains the results for metrics data.

func (*MetricsResult) BounceRate

func (mr *MetricsResult) BounceRate() float64

BounceRate returns the bounce rate associated with this result. It will return 0 (zero) if the bounce rate information is not present.

func (*MetricsResult) VisitDuration

func (mr *MetricsResult) VisitDuration() float64

VisitDuration returns the visit duration associated with this result. It will return 0 (zero) if the visit duration information is not present.

type Properties

type Properties []Property

Properties represents a list of properties.

Example
package main

import (
	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// A list of properties with an OS and Browser
	_ = plausible.Properties{
		{Name: plausible.VisitOs, Value: "Windows"},
		{Name: plausible.VisitBrowser, Value: "Firefox"},
	}
}
Output:

func (*Properties) Add

func (p *Properties) Add(property Property)

Add adds a property to the list.

func (*Properties) Count

func (p *Properties) Count() int

Count returns the number of properties in the list.

type Property

type Property struct {
	// Name is the name of the property
	Name PropertyName
	// Value is the value associated with the property
	Value string
}

Property represents a Plausible property, consisting of a name and value. Properties are used when building filters for queries

func CustomProperty

func CustomProperty(propertyName string, value string) Property

CustomProperty makes a Property out of a custom name and value for that property.

type PropertyName

type PropertyName string

PropertyName represents the name of a property. Check the constants of this package to see a list of PropertyName values ready to use.

func CustomPropertyName

func CustomPropertyName(propertyName string) PropertyName

CustomPropertyName makes a PropertyName for a custom property with a given name. A custom PropertyName is needed to create a Property related to a custom event. Also check the function CustomProperty for an easy way to create a property with a value and a custom name.

func (*PropertyName) IsEmpty

func (pn *PropertyName) IsEmpty() bool

IsEmpty tells whether the name of the property is empty

type PropertyResult

type PropertyResult struct {
	// Name contains a value of the event name property.
	// This value must only be only if the breakdown query was for this property.
	Name string `json:"name"`
	// Page contains a value of the event page property.
	// This value must only be only if the breakdown query was for this property.
	Page string `json:"page"`
	// Page contains a value of the visit source property.
	// This value must only be only if the breakdown query was for this property.
	Source string `json:"source"`
	// Referrer contains a value of the visit referrer property.
	// This value must only be only if the breakdown query was for this property.
	Referrer string `json:"referrer"`
	// UtmMedium contains a value of the utm medium property.
	// This value must only be only if the breakdown query was for this property.
	UtmMedium string `json:"utm_medium"`
	// UtmSource contains a value of the utm source property.
	// This value must only be only if the breakdown query was for this property.
	UtmSource string `json:"utm_source"`
	// UtmCampaign contains a value of the utm campaign property.
	// This value must only be only if the breakdown query was for this property.
	UtmCampaign string `json:"utm_campaign"`
	// Device contains a value of the device property.
	// This value must only be only if the breakdown query was for this property.
	Device string `json:"device"`
	// Browser contains a value of the browser property.
	// This value must only be only if the breakdown query was for this property.
	Browser string `json:"browser"`
	// BrowserVersion contains a value of the browser version property.
	// This value must only be only if the breakdown query was for this property.
	BrowserVersion string `json:"browser_version"`
	// OS contains a value of the operating system property.
	// This value must only be only if the breakdown query was for this property.
	OS string `json:"os"`
	// OSVersion contains a value of the operating system version property.
	// This value must only be only if the breakdown query was for this property.
	OSVersion string `json:"os_version"`
	// Country contains a value of the country property.
	// This value must only be only if the breakdown query was for this property.
	Country string `json:"country"`
}

PropertyResult contains the value of a property for an entry in the breakdown query results. At any moment, only the field corresponding to the property indicated in the query must be used. All the other fields will be empty.

type QueryArg

type QueryArg struct {
	// Name is the name of the query argument
	Name string
	// Value is the value for the query argument
	Value string
}

QueryArg represents a query argument

type QueryArgs

type QueryArgs []QueryArg

QueryArgs represents a list of query arguments.

func (*QueryArgs) Add

func (qa *QueryArgs) Add(q QueryArg) *QueryArgs

Add adds a query argument to the list.

func (*QueryArgs) Count

func (qa *QueryArgs) Count() int

Count returns the number of query arguments in the list

func (*QueryArgs) Merge

func (qa *QueryArgs) Merge(qArgsList ...QueryArgs) *QueryArgs

Merge adds together the query arguments in other lists to the current one.

type SharedLinkRequest added in v0.2.0

type SharedLinkRequest struct {
	// Name is the name of the shared link.
	// This field is required.
	Name string
}

SharedLinkRequest represents a shared link request

func (*SharedLinkRequest) Validate added in v0.2.0

func (q *SharedLinkRequest) Validate() (bool, string)

Validate validates if a shared link request is valid

type SharedLinkResult added in v0.2.0

type SharedLinkResult struct {
	// Name is the name of the shared link
	Name string `json:"name"`
	// URL is the URL for the shared link
	URL string `json:"url"`
}

SharedLinkResult represents the result of a shared link request

type Site

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

Site represents a site added to plausible and implements a client for all stats requests related with the site.

Site is safe for concurrent use.

func (*Site) Aggregate

func (s *Site) Aggregate(query AggregateQuery) (AggregateResult, error)

Aggregate performs an aggregate query. An aggregate query reports data for metrics aggregated over a period of time, eg, "total number of visitors/pageviews for a particular day".

Example
package main

import (
	"fmt"

	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Create a client with an API token
	client := plausible.NewClient("<your_api_token>")

	// Get an handler to perform queries for a given site
	mysite := client.Site("example.com")

	// Get all visitors for today
	todaysVisitorsQuery := plausible.AggregateQuery{
		Period: plausible.DayPeriod(),
		Metrics: plausible.Metrics{
			plausible.Visitors,
		},
	}

	result, err := mysite.Aggregate(todaysVisitorsQuery)
	if err != nil {
		// handle error
	}
	fmt.Printf("Total visitors of %s today: %d\n", mysite.ID(), result.Visitors)
}
Output:

func (*Site) Breakdown

func (s *Site) Breakdown(query BreakdownQuery) (BreakdownResult, error)

Breakdown performs a breakdown query. A breakdown query reports stats for the value of a given property over a period of time, e.g, "total number of visitors and page views for each operating system in the last month".

Example
package main

import (
	"fmt"

	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Create a client with an API token
	client := plausible.NewClient("<your_api_token>")

	// Get an handler to perform queries for a given site
	mysite := client.Site("example.com")

	// For each page, return the number of visitors and page views in the last 7 days
	pageBreakdownQuery := plausible.BreakdownQuery{
		Property: plausible.EventPage,
		Period:   plausible.Last7Days(),
		Metrics: plausible.Metrics{
			plausible.Visitors,
			plausible.PageViews,
		},
	}

	pageBreakdown, err := mysite.Breakdown(pageBreakdownQuery)
	if err != nil {
		// handle error
	}

	for _, stat := range pageBreakdown {
		fmt.Printf("Page: %s | Visitors: %d | Pageviews: %d\n", stat.Page, stat.Visitors, stat.Pageviews)
	}
}
Output:

func (*Site) CurrentVisitors

func (s *Site) CurrentVisitors() (int, error)

CurrentVisitors gets the current visitors for the site.

Example
package main

import (
	"fmt"

	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Create a client with an API token
	client := plausible.NewClient("<your_api_token>")

	// Get an handler to perform queries for a given site
	mysite := client.Site("example.com")

	// Get the current visitors
	visitors, err := mysite.CurrentVisitors()
	if err != nil {
		// handle error
	}

	fmt.Printf("Site %s has %d current visitors!\n", mysite.ID(), visitors)
}
Output:

func (*Site) ID

func (s *Site) ID() string

ID returns the ID of the site.

func (s *Site) SharedLink(query SharedLinkRequest) (SharedLinkResult, error)

SharedLink creates a shared link with a given name. If the link already exists, its information will be returned.

Note: This endpoint requires an API token with permissions to use the sites provisioning API. Check https://plausible.io/docs/sites-api for more info

func (*Site) Timeseries

func (s *Site) Timeseries(query TimeseriesQuery) (TimeseriesResult, error)

Timeseries performs a time series query. A time series query reports a list of data points over a period of time, where each data point contains data about metrics for that period of time. e.g, "total number of visitors and page views for each day in the last month".

Example
package main

import (
	"fmt"

	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Create a client with an API token
	client := plausible.NewClient("<your_api_token>")

	// Get an handler to perform queries for a given site
	mysite := client.Site("example.com")

	// For each day of the last 7 days of the 1st of February 2021,
	// get the number of visitors and page views.
	tsQuery := plausible.TimeseriesQuery{
		Period: plausible.Last7Days().FromDate(plausible.Date{Day: 1, Month: 2, Year: 2021}),
		Metrics: plausible.Metrics{
			plausible.Visitors,
			plausible.PageViews,
		},
		Interval: plausible.DateInterval,
	}

	queryResults, err := mysite.Timeseries(tsQuery)
	if err != nil {
		// handle error
	}

	// Iterate over the data points
	for _, stat := range queryResults {
		fmt.Printf("Date: %s | Visitors: %d | Pageviews: %d\n", stat.Date, stat.Visitors, stat.Pageviews)
	}
}
Output:

type Time

type Time struct {
	// Hour of a given time of day
	Hour int
	// Minute of a given time of day
	Minute int
	// Second of a given time of day
	Second int
}

Time represents the basic information about a time of day. It represents the information about time returned by some API calls.

func (*Time) String

func (t *Time) String() string

String converts the Time into a human-readable string.

type TimeInterval

type TimeInterval string

TimeInterval represents an interval of time by which each entry in the query results must be separated by.

func (*TimeInterval) IsEmpty

func (t *TimeInterval) IsEmpty() bool

IsEmpty tells whether the time interval has information.

type TimePeriod

type TimePeriod struct {
	// Period is a string representing a period of time, e.g "6mo", "12mo", "7d", "30d", "custom", "month", "day" or "custom".
	// This field is mandatory.
	Period string
	// Date is a string representing a date to which the time period refers to, in the format of "yyyy-mm-dd"
	// This field is optional.
	Date string
}

TimePeriod represents a period of time for which to get the results.

TimePeriod provides low-level access to the API. For most users, it is recommended to use one of the methods in this package that returns a time period to build a time period, instead of using this struct directly.

func CustomPeriod

func CustomPeriod(fromDate Date, toDate Date) TimePeriod

CustomPeriod allows to build a custom time period/range between the two given dates.

Example
package main

import (
	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Get the period for the last 12 months from the 1st of January 2021
	plausible.Last12Months().FromDate(plausible.Date{Day: 1, Month: 1, Year: 2021})
}
Output:

func DayPeriod

func DayPeriod() TimePeriod

DayPeriod returns a time period referring to a day. If no additional date information is given, this defaults to mean "today". To change the day to which this date refers to, chain the return of this function with OfDate or FromDate to add date information to the time period.

func Last12Months

func Last12Months() TimePeriod

Last12Months returns a time period referring to the last 12 months. To change the date from which the "last 6 months" refer to, chain the return of this function with OfDate or FromDate to add date information to the time period.

func Last30Days

func Last30Days() TimePeriod

Last30Days returns a time period referring to the last 30 days. To change the date from which the "last 30 days" refer to, chain the return of this function with OfDate or FromDate to add date information to the time period.

func Last6Months

func Last6Months() TimePeriod

Last6Months returns a time period referring to the last 6 months. To change the date from which the "last 6 months" refer to, chain the return of this function with OfDate() or FromDate() to add date information to the time period.

Example
package main

import (
	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Get the period for the last 6 months from today
	plausible.Last6Months()
}
Output:

func Last7Days

func Last7Days() TimePeriod

Last7Days returns a time period referring to the last 7 days. To change the date from which the "last 7 days" refer to, chain the return of this function with OfDate or FromDate to add date information to the time period.

func MonthPeriod

func MonthPeriod() TimePeriod

MonthPeriod returns a time period referring to a month. If no additional date information is given, this defaults to mean "the current month". To change the month to which this date refers to, chain the return of this function with OfDate or FromDate to add date information to the time period.

func (TimePeriod) FromDate

func (tp TimePeriod) FromDate(date Date) TimePeriod

FromDate adds date information to a time period.

Example
package main

import (
	"github.com/andrerfcsantos/go-plausible/plausible"
)

func main() {
	// Get the period for the first 15 days of 2021
	plausible.CustomPeriod(plausible.Date{Day: 1, Month: 1, Year: 2021}, plausible.Date{Day: 15, Month: 1, Year: 2021})
}
Output:

func (TimePeriod) IsEmpty

func (tp TimePeriod) IsEmpty() bool

IsEmpty tells whether the time period is empty

func (TimePeriod) OfDate

func (tp TimePeriod) OfDate(date Date) TimePeriod

OfDate adds date information to a time period. An alias of FromDate.

type TimeseriesDataPoint

type TimeseriesDataPoint struct {
	// Date is a string containing information about the date this result refers to in the format of "yyyy-mm-dd".
	// For some queries, this string will also include information about an hour of day, in the format "yyyy-mm-dd hh:mm:ss"
	Date string `json:"date"`
	// MetricsResult contains the metric results for the metrics included in the query
	MetricsResult
}

TimeseriesDataPoint represents a data point in a time series result.

type TimeseriesQuery

type TimeseriesQuery struct {
	// Period to consider for the time series query.
	// The result will include results over this period of time.
	// This field is mandatory.
	Period TimePeriod
	// Filters is a filter over properties to narrow down the time series results.
	// This field is optional.
	Filters Filter
	// Metrics to be included in the time series information.
	// This field is optional.
	Metrics Metrics
	// Interval of time to consider for the time series result.
	// This field is optional.
	Interval TimeInterval
}

TimeseriesQuery represents an API query for time series information over a period of time. In an aggregate query, the Metrics field is mandatory, all the others are optional.

func (*TimeseriesQuery) Validate

func (aq *TimeseriesQuery) Validate() (ok bool, invalidReason string)

Validate tells whether the query is valid or not. If the query is not valid, a string explaining why the query is not valid will be returned.

type TimeseriesResult

type TimeseriesResult []TimeseriesDataPoint

TimeseriesResult represents the result of a time series query.

Jump to

Keyboard shortcuts

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