Go SDK

Unpublished

Stdlib only, zero dependencies, arbitrary precision via math/big.

Initialize

NewClient returns an error if the API key is missing. The package name is counters; the import path ends in /go, so alias it. BaseURL defaults to the production host.

main.go
package main

import (
	"context"
	"fmt"
	"os"

	counters "github.com/counters-dot-dev/counters.dev-sdk/go"
)

func main() {
	client, err := counters.NewClient(counters.Options{
		APIKey: os.Getenv("COUNTERS_API_KEY"),
	})
	if err != nil {
		panic(err)
	}
	defer client.Close()
	// ...
}

Count

Add and Subtract are buffered and coalesced per counter (flushed as one POST /batch). AddNow/SubtractNow write immediately and return the counter; they take a context. amount accepts int, int64, string, or *big.Int.

count
reg, err := client.Counter("registrations")
if err != nil {
	panic(err)
}

reg.Add(1)     // buffered
reg.Add(5)     // coalesced
client.Flush() // one POST /batch

c, err := reg.AddNow(context.Background(), 1) // immediate
if err != nil {
	panic(err)
}
fmt.Println(c.Value) // "42" — a string

Read

Read the current value, or a per-bucket time series. SeriesParams.From/To are time.Time values.

read
v, err := reg.Value(context.Background())
// v.Value is a string

series, err := reg.Series(context.Background(), counters.SeriesParams{
	From:   time.Now().Add(-7 * 24 * time.Hour),
	To:     time.Now(),
	Bucket: "1d",
})

Manage

Clear resets to zero (new epoch, history retained); Delete tombstones the counter; List pages the organization's counters.

manage
_, err = reg.Clear(ctx)
err = reg.Delete(ctx)

page, err := client.List(ctx, "", 50) // cursor, limit

Lifecycle

Buffered writes flush on an interval and at MaxBatchSize. defer client.Close() flushes and stops the background timer before your program exits.

lifecycle
defer client.Close() // flush + stop the background timer

Errors

Client-side validation returns *ValidationError. Non-2xx responses return *APIError with Status and Title; match it with errors.As.

errors
c, err := reg.AddNow(ctx, 1)
if err != nil {
	var apiErr *counters.APIError
	if errors.As(err, &apiErr) {
		fmt.Println(apiErr.Status, apiErr.Title)
	}
}
Prefer raw HTTP? See the REST API reference. Create a key in your dashboard.