Go SDK
UnpublishedStdlib only, zero dependencies, arbitrary precision via math/big.
Not yet published
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.
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.
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 stringRead
Read the current value, or a per-bucket time series. SeriesParams.From/To are time.Time values.
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.
_, err = reg.Clear(ctx)
err = reg.Delete(ctx)
page, err := client.List(ctx, "", 50) // cursor, limitLifecycle
Buffered writes flush on an interval and at MaxBatchSize. defer client.Close() flushes and stops the background timer before your program exits.
defer client.Close() // flush + stop the background timerErrors
Client-side validation returns *ValidationError. Non-2xx responses return *APIError with Status and Title; match it with errors.As.
c, err := reg.AddNow(ctx, 1)
if err != nil {
var apiErr *counters.APIError
if errors.As(err, &apiErr) {
fmt.Println(apiErr.Status, apiErr.Title)
}
}