Examples
Every example here is a function in client/example_test.go. go test runs each one against an in-process server and compares what it prints with its Output comment, so these cannot drift from the API.
The whole loop
Example shows the whole loop: connect, write, read back.
func Example() {
srv, err := clienttest.NewServer()
if err != nil {
fmt.Println("start server:", err)
return
}
defer func() { _ = srv.Close() }()
c, err := client.Dial(srv.Addr(), client.Options{})
if err != nil {
fmt.Println("dial:", err)
return
}
defer func() { _ = c.Close() }()
ctx := context.Background()
stream := client.NewStreamID("binance", "BTCUSDT", "1m")
// DurabilityAcked is the zero value: this blocks until the batch is in
// the write-ahead log and the log is fsynced.
if ierr := c.IngestCandles(ctx, stream, exampleCandles(5), client.DurabilityAcked); ierr != nil {
fmt.Println("ingest:", ierr)
return
}
resp, err := c.QueryCandles(ctx, client.QueryRequest{
StreamID: stream,
StartTime: exampleBase.UnixNano(),
EndTime: exampleBase.Add(5 * time.Minute).UnixNano(),
})
if err != nil {
fmt.Println("query:", err)
return
}
fmt.Printf("status=%d points=%d first_close=%.2f\n",
resp.Status, len(resp.Points), resp.Points[0].Candle.Close)
// Output:
// status=0 points=5 first_close=67104.00
}
Rows
Example_rows pages a range without the caller writing a pagination loop. MaxResults is a TOTAL cap across pages, not a per-page one.
func Example_rows() {
srv, _ := clienttest.NewServer()
defer func() { _ = srv.Close() }()
c, _ := client.Dial(srv.Addr(), client.Options{})
defer func() { _ = c.Close() }()
stream := client.NewStreamID("binance", "BTCUSDT", "1m")
srv.SeedCandles(stream, exampleCandles(10))
rows := c.QueryCandlesRows(context.Background(), client.QueryRequest{
StreamID: stream,
StartTime: exampleBase.UnixNano(),
EndTime: exampleBase.Add(time.Hour).UnixNano(),
})
defer func() { _ = rows.Close() }()
n := 0
for rows.Next() {
if p := rows.Point(); !p.IsGap {
n++
}
}
// ALWAYS check Err after the loop: an in-band refusal (no such stream)
// ends iteration exactly like a normal finish.
if err := rows.Err(); err != nil {
fmt.Println("rows:", err)
return
}
fmt.Println("candles:", n)
// Output:
// candles: 10
}
Multi query
Example_multiQuery asks for several windows in ONE round trip. Nothing is merged: results come back as separate series, in request order, which is what lets the same stream appear twice with different ranges.
func Example_multiQuery() {
srv, _ := clienttest.NewServer()
defer func() { _ = srv.Close() }()
c, _ := client.Dial(srv.Addr(), client.Options{})
defer func() { _ = c.Close() }()
btc := client.NewStreamID("binance", "BTCUSDT", "1m")
eth := client.NewStreamID("binance", "ETHUSDT", "1m")
srv.SeedCandles(btc, exampleCandles(10))
srv.SeedCandles(eth, exampleCandles(4))
results, err := c.QueryMultiAll(context.Background(), []client.QueryRequest{
{StreamID: btc, StartTime: exampleBase.UnixNano(), EndTime: exampleBase.Add(time.Hour).UnixNano()},
{StreamID: eth, StartTime: exampleBase.UnixNano(), EndTime: exampleBase.Add(time.Hour).UnixNano()},
// The same stream again, a narrower window — legal because results
// are keyed by POSITION, not by stream id.
{StreamID: btc, StartTime: exampleBase.UnixNano(), EndTime: exampleBase.Add(3 * time.Minute).UnixNano()},
})
if err != nil {
fmt.Println("multi:", err)
return
}
for i, r := range results {
fmt.Printf("result %d: status=%d candles=%d\n", i, r.Status, len(r.Points))
}
// Output:
// result 0: status=0 candles=10
// result 1: status=0 candles=4
// result 2: status=0 candles=3
}
Batcher
Example_batcher accumulates records and sends them on whichever threshold is reached first: MaxRecords, or MaxDelay measured from the OLDEST buffered record. Close is not optional. Add returns when a record is BUFFERED, so a failed flush surfaces later — and Close is the one place a caller is guaranteed to hear about it, as well as what sends the final partial batch.
func Example_batcher() {
srv, _ := clienttest.NewServer()
defer func() { _ = srv.Close() }()
c, _ := client.Dial(srv.Addr(), client.Options{})
defer func() { _ = c.Close() }()
stream := client.NewStreamID("binance", "BTCUSDT", "1m")
b, err := client.NewCandleBatcher(c, stream, client.BatchOptions{
MaxRecords: 4,
MaxDelay: 50 * time.Millisecond,
})
if err != nil {
fmt.Println("batcher:", err)
return
}
for _, candle := range exampleCandles(10) {
if err := b.Add(context.Background(), candle); err != nil {
fmt.Println("add:", err)
return
}
}
if err := b.Close(); err != nil {
fmt.Println("close:", err)
return
}
resp, _ := c.QueryCandles(context.Background(), client.QueryRequest{
StreamID: stream,
StartTime: exampleBase.UnixNano(),
EndTime: exampleBase.Add(time.Hour).UnixNano(),
})
fmt.Println("stored:", len(resp.Points))
// Output:
// stored: 10
}
Subscribe
Example_subscribe consumes a live stream. Event.Live marks the backfill-to-live pivot, and Event.Dropped counts batches the server shed — records that are GONE, not delayed.
func Example_subscribe() {
srv, _ := clienttest.NewServer()
defer func() { _ = srv.Close() }()
c, _ := client.Dial(srv.Addr(), client.Options{})
defer func() { _ = c.Close() }()
stream := client.NewStreamID("binance", "BTCUSDT", "1m")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
sub, err := c.SubscribeStream(ctx, client.SubscribeRequest{StreamID: stream})
if err != nil {
fmt.Println("subscribe:", err)
return
}
defer func() { _ = sub.Close() }()
go srv.PublishCandles(stream, exampleCandles(3))
if !sub.Next(ctx) {
fmt.Println("next:", sub.Err())
return
}
ev := sub.Event()
fmt.Printf("records=%d dropped=%d\n", ev.Records(), ev.Dropped)
// Output:
// records=3 dropped=0
}
Error handling
Example_errorHandling shows the two error shapes a caller branches on: an in-band query status (the request was fine, the data is not there) and a transport-level refusal (the server said no).
func Example_errorHandling() {
srv, _ := clienttest.NewServer()
defer func() { _ = srv.Close() }()
c, _ := client.Dial(srv.Addr(), client.Options{
Retry: client.RetryOptions{MaxAttempts: 1}, // do not absorb the shed below
})
defer func() { _ = c.Close() }()
ctx := context.Background()
stream := client.NewStreamID("binance", "NOSUCH", "1m")
// In-band: a missing stream is a STATUS, not an error. The call succeeded.
resp, err := c.QueryCandles(ctx, client.QueryRequest{
StreamID: stream,
StartTime: exampleBase.UnixNano(),
EndTime: exampleBase.Add(time.Minute).UnixNano(),
})
fmt.Printf("err=%v status_is_not_found=%t\n", err, resp.Status == client.QueryStatusStreamNotFound)
// Transport: the server refused. Reach the code with errors.As, and ask
// RetryAfter whether retrying is appropriate at all.
srv.FailNext(client.ErrorCodeOverloaded, "wal buffer full")
err = c.IngestCandles(ctx, stream, exampleCandles(1), client.DurabilityAcked)
var remote *client.RemoteError
if errors.As(err, &remote) {
_, retryable := remote.RetryAfter()
fmt.Printf("code=%d retryable=%t\n", remote.Code, retryable)
}
// Output:
// err=<nil> status_is_not_found=true
// code=7 retryable=true
}
Resilient client
Example_resilientClient survives a dropped connection. The split worth knowing: READS retry across a reconnect, WRITES do not — a connection lost while an ingest was in flight returns ErrAmbiguous, because the batch may or may not be stored and this SDK will not guess.
func Example_resilientClient() {
srv, _ := clienttest.NewServer()
defer func() { _ = srv.Close() }()
c, err := client.DialResilient(srv.Addr(), client.Options{}, client.ResilienceOptions{
MaxAttempts: 3,
Backoff: time.Millisecond,
})
if err != nil {
fmt.Println("dial:", err)
return
}
defer func() { _ = c.Close() }()
stream := client.NewStreamID("binance", "BTCUSDT", "1m")
srv.SeedCandles(stream, exampleCandles(6))
resp, err := c.QueryCandles(context.Background(), client.QueryRequest{
StreamID: stream,
StartTime: exampleBase.UnixNano(),
EndTime: exampleBase.Add(time.Hour).UnixNano(),
})
if err != nil {
fmt.Println("query:", err)
return
}
fmt.Printf("points=%d state=%v\n", len(resp.Points), c.State())
// Output:
// points=6 state=connected
}
Query columns
ExampleClient_QueryColumns reads one column of a range: the node decodes and sends the timestamps and the closes, and the batch holds two slices instead of a struct per candle.
func ExampleClient_QueryColumns() {
srv, err := clienttest.NewServer()
if err != nil {
fmt.Println("start server:", err)
return
}
defer func() { _ = srv.Close() }()
c, err := client.Dial(srv.Addr(), client.Options{})
if err != nil {
fmt.Println("dial:", err)
return
}
defer func() { _ = c.Close() }()
ctx := context.Background()
stream := client.NewStreamID("binance", "BTCUSDT", "1m")
if ierr := c.IngestCandles(ctx, stream, exampleCandles(5), client.DurabilityAcked); ierr != nil {
fmt.Println("ingest:", ierr)
return
}
cols, err := c.QueryColumns(ctx, client.QueryRequest{
StreamID: stream,
StartTime: exampleBase.UnixNano(),
EndTime: exampleBase.Add(5 * time.Minute).UnixNano(),
Columns: client.ColumnClose, // the stamps and the close, nothing else
})
if err != nil {
fmt.Println("query:", err)
return
}
fmt.Printf("rows=%d first_close=%.2f last_close=%.2f has_open=%t\n",
cols.Len(), cols.Close[0], cols.Close[cols.Len()-1], cols.Open != nil)
// Output: rows=5 first_close=67104.00 last_close=67108.00 has_open=false
}