Go
Send events and read stats from Go. Standard library only, Go 1.21+.
Install from source
The module isn't published yet. Point your module at a checkout of the Stancelens repository with a replace directive:
go mod edit -replace github.com/stancedev/stancelens/packages/go=/path/to/stancelens/packages/go
go get github.com/stancedev/stancelens/packages/go@v0.0.0import stancelens "github.com/stancedev/stancelens/packages/go"You need an API key from an owner or admin of the site (Account → API keys). Keep it on the server: it can write events and erase users.
Track events
client, err := stancelens.New(stancelens.Config{
APIKey: os.Getenv("STANCELENS_API_KEY"),
SiteID: "SITE_ID",
})
if err != nil {
log.Fatal(err)
}
defer client.Close(context.Background())
client.Track(stancelens.Event{Name: "signup", UID: "user_42", Props: map[string]any{"plan": "pro"}})
client.Identify(stancelens.Event{UID: "user_42", VID: anonIDFromBrowser, Traits: map[string]any{"company": "Acme"}})
client.Revenue("purchase", 49, "USD", stancelens.Event{UID: "user_42"})
client.Pageview(stancelens.Event{URL: "https://example.com/pricing", IP: ip, UA: userAgent})These only queue the event. They return an error only for a bad event (ErrNoName, ErrNoIdentity, ErrNoPage), a full queue (ErrQueueFull) or a closed client (ErrClosed). A background goroutine sends batches of up to 100 when FlushAt events are queued or every FlushInterval.
Flush(ctx)sends everything queued and waits. Ifctxends first it returnsctx.Err(); the requests are cancelled and the events stay queued.Close(ctx)flushes, then stops the goroutine; safe to call more than once. Events still unsent whenctxends go toOnError. Go has no exit hook, so callCloseyourself (withdeferinmain, or in your SIGTERM handler).- Every event needs
UID,VIDorIP.VIDis used as given; with onlyIP(and ideallyUA) the server derives the daily-rotating anonymous ID; with onlyUID, it's also sent as the visitor ID.
Event fields
Name, UID, VID, URL, Path, Referrer, Title, Props (strings, numbers, booleans, nil; up to 50 keys), Revenue (*Revenue{Amount, Currency}), Timestamp (defaults to the call time; up to 30 days back), IP, UA, Language, Timezone (IANA name, used for the country estimate), Duration, Traits, AppVersion. Events are sent with platform: "server" and sdk: "stancelens-go/<version>". A page view that carries a browser's user agent is recorded as web, so server-side page views count with browser traffic; everything else is server.
Config
| Field | Default | |
|---|---|---|
Host | https://stancelens.com | Your Stancelens URL |
FlushAt | 20 | Send when this many are queued |
FlushInterval | 5s | Send whatever is queued |
MaxQueueSize | 10000 | Track returns ErrQueueFull past it |
MaxRetries | 3 | Network errors, 408, 429, 5xx; honours Retry-After; negative means none |
Timeout | 10s | Per request |
HTTPClient | new client | |
OnError | log | func(err error, events []Event) for undelivered events |
Logger | slog.Default() | |
Disabled | false | Accept calls, send nothing |
client.Dropped() counts events that weren't stored: queue full, sent after Close, failed after retries, or refused by the server (bot user agent, excluded path, invalid).
Read stats
ctx := context.Background()
q := stancelens.Query{Period: "7d", Filters: map[string]string{"country": "US,DE"}}
agg, err := client.Stats.Aggregate(ctx, q, "visitors", "pageviews", "revenue")
fmt.Println(agg.Results["visitors"].Value)
ts, err := client.Stats.Timeseries(ctx, stancelens.Query{Period: "30d", Interval: "day"})
bd, err := client.Stats.Breakdown(ctx, "path", q, 10, 1) // limit, page (0 = default)
rt, err := client.Stats.Realtime(ctx)
rows, err := client.Stats.Export(ctx, stancelens.Query{Period: "today", Filters: map[string]string{"user_id": "user_42"}})
del, err := client.Stats.DeleteUser(ctx, "user_42") // erasure, owner or admin key- Non-2xx answers come back as
*stancelens.APIErrorwithStatus,MessageandBody(Statusis 0 when the server couldn't be reached). Check witherrors.As. Query.Period:today,yesterday,24h,7d,30d(server default),mtd,lastmonth,90d,6mo,12mo,ytd,all, in the site timezone (details).From/To(inclusive; each sends its UTC calendar day) select a custom range of site-local days.Query.Filters:{dimension: value}. A comma means any of;!excludes,~means contains. Dimensions are the API filter dimensions.
Server-side page views (net/http)
handler := client.Middleware(stancelens.MiddlewareOptions{
UserID: func(r *http.Request) string { return userIDFromCookie(r) },
Skip: func(r *http.Request) bool { return strings.HasPrefix(r.URL.Path, "/admin") },
TrustProxy: false, // true behind a proxy that sets X-Forwarded-For / X-Forwarded-Proto
})(mux)
http.ListenAndServe(":8080", handler)The middleware records a page view for each successful (2xx) GET that responds with text/html and isn't a browser prefetch, with the visitor's IP, user agent, referrer and language. UserID runs after your handler with the request the middleware received, so read the user from the request itself (a cookie or header), not from context values inner middleware adds. Use it instead of the browser script on those pages, not with it.