// Package plausible reads visit numbers from Plausible's Stats API v2 // (https://plausible.io/docs/stats-api), on plausible.io or a self-hosted // Plausible such as the one on a Federated Core. package plausible import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "strings" "time" ) // ErrUnauthorized means the key was refused. var ErrUnauthorized = errors.New("Plausible refused the API key") // Client calls one Plausible with one key. type Client struct { base, key string http *http.Client } // New takes Plausible's address (e.g. https://plausible.example.com) and a // Stats API key. func New(base, key string) *Client { return &Client{base: strings.TrimRight(base, "/"), key: key, http: &http.Client{Timeout: time.Minute}} } // Query is a Stats API v2 query. type Query struct { SiteID string `json:"site_id"` Metrics []string `json:"metrics"` DateRange any `json:"date_range"` // "7d", or ["2026-11-01", "2026-11-21"] Dimensions []string `json:"dimensions,omitempty"` Filters [][]any `json:"filters,omitempty"` Pagination *Pagination `json:"pagination,omitempty"` } // Pagination limits the rows. type Pagination struct { Limit int `json:"limit"` Offset int `json:"offset"` } // Row is one result: the dimensions' values, then the metrics'. type Row struct { Metrics []float64 `json:"metrics"` Dimensions []string `json:"dimensions"` } // Run sends a query. func (c *Client) Run(ctx context.Context, q Query) ([]Row, error) { body, err := json.Marshal(q) if err != nil { return nil, err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+"/api/v2/query", bytes.NewReader(body)) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+c.key) req.Header.Set("Content-Type", "application/json") res, err := c.http.Do(req) if err != nil { return nil, err } defer res.Body.Close() raw, err := io.ReadAll(io.LimitReader(res.Body, 32<<20)) if err != nil { return nil, err } if res.StatusCode == http.StatusUnauthorized { return nil, ErrUnauthorized } if res.StatusCode != http.StatusOK { var e struct { Error string `json:"error"` } if json.Unmarshal(raw, &e) == nil && e.Error != "" { return nil, fmt.Errorf("Plausible: %s", e.Error) } return nil, fmt.Errorf("Plausible: HTTP %d: %s", res.StatusCode, strings.TrimSpace(string(raw[:min(len(raw), 300)]))) } var out struct { Results []Row `json:"results"` } if err := json.Unmarshal(raw, &out); err != nil { return nil, fmt.Errorf("Plausible: %w", err) } return out.Results, nil } // Visitors is a site's visitors over the last 30 days: a cheap check that // the key can read the site. func (c *Client) Visitors(ctx context.Context, site string) (int, error) { rows, err := c.Run(ctx, Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: "30d"}) if err != nil { return 0, err } if len(rows) == 0 || len(rows[0].Metrics) == 0 { return 0, nil } return int(rows[0].Metrics[0]), nil }