> ## Documentation Index
> Fetch the complete documentation index at: https://docs.useshipd.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Go SDK reference

> Go client options, evaluation methods, identify events, and lifecycle methods.

## Overview

Import `github.com/alasti-company/useshipd.com/sdks/go` as `shipd`. All evaluation methods are safe to call concurrently and run locally. See [Go](/sdks/go) for installation and a complete example.

## New

```go theme={null}
func New(options Options) (*Client, error)
```

**options.SDKKey** `string` *required*

The environment's server SDK key.

| Option | Default |
| - | - |
| `Defaults` | JSON-compatible values by flag key |
| `RefreshInterval` | `30 * time.Second` |
| `FetchTimeout` | `10 * time.Second` |
| `DisablePolling` | `false`; initial fetch still runs |
| `DisableEvents` | `false` |
| `FlushAt` | `50`; flush once this many events are buffered (at most 200). Negative flushes on the interval only |
| `FlushInterval` | `5 * time.Second`. Negative disables timed flushes |
| `Bootstrap` | None. A snapshot (the JSON body of `GET /sdk/v1/snapshot`) served until a newer one is fetched. Makes the client ready immediately; invalid snapshots fail `New` |
| `Overrides.UnsafeEndpoint` | Empty, which uses `https://edge.useshipd.com` (`shipd.DefaultEndpoint`). **Unsafe:** for shipd development and tests only, because the URL receives your SDK key. Surrounding whitespace and trailing slashes are trimmed; a plaintext `http` URL to a non-local host logs a warning |
| `HTTPClient` | Default HTTP client, which rejects redirects |

Zero durations select defaults. Negative `RefreshInterval` and `FetchTimeout` values are rejected; negative flush options behave as shown above. Custom HTTP clients must honor request contexts and control their own redirect behavior.

**Returns** a client that immediately starts fetching a snapshot.

**Errors.** Invalid configuration returns an error. Background fetch failures are exposed through `LastError`.

## Evaluation methods

```go theme={null}
func (c *Client) IsEnabled(key string, ctx EvaluationContext) bool
func (c *Client) GetVariant(key string, ctx EvaluationContext) string
func (c *Client) GetNumber(key string, ctx EvaluationContext) float64
func (c *Client) GetJSON(key string, ctx EvaluationContext) any
func (c *Client) Evaluate(key string, ctx EvaluationContext) Result
```

**key** `string` *required*

The flag key, such as `new-checkout`.

**ctx** `EvaluationContext` *required*

Request-scoped `UserID`, scalar `Attributes`, and optional `SegmentIDs`. Use `shipd.EvaluationContext{}` for anonymous evaluation. Set `UserIDPresent: true` to compare an explicitly empty `UserID`; empty IDs do not satisfy `exists` or provide a rollout bucket.

**Returns** the evaluated value. `Evaluate` also returns `Reason`, `RuleID`, and a nullable `SnapshotVersion`. JSON values are copied, and JSON numbers decode as `float64`.

**Fallback.** Before a snapshot loads or for an unknown key, configured defaults apply. Built-in typed defaults are `false`, `"control"`, `0`, and an empty JSON object. Disabled flags use the snapshot default. Boolean, variant, and number getters use a correctly typed configured default, or their built-in default, when the resulting value has the wrong type. `Evaluate` uses `nil` for an unknown key without a configured default.

**Errors.** Evaluation methods return values without errors. Failed refreshes keep the last valid snapshot. Evaluation continues after `Close` with the last snapshot or defaults. Evaluation values that exceed the event payload limit are omitted from telemetry.

## Ready

```go theme={null}
func (c *Client) Ready(ctx context.Context) error
```

Waits for the initial snapshot fetch. Provide a deadline to bound startup waiting.

**Returns** `nil` once a snapshot loads, or immediately when `Bootstrap` is set.

**Errors.** Returns the initial fetch error as soon as that attempt fails. The client then serves defaults, and polling (unless disabled) keeps trying. Returns the context error on timeout or cancellation while the first fetch is still in flight, or `ErrClosed` after close, even if a snapshot previously loaded.

## Refresh

```go theme={null}
func (c *Client) Refresh(ctx context.Context) error
```

Fetches the current snapshot with ETag support. Concurrent refreshes are serialized. Lower snapshot versions are ignored. Snapshots with malformed evaluation data are rejected as a whole.

**Returns** `nil` for a successful fetch or `304` response with an existing snapshot.

**Errors.** Request, response, and parsing errors are returned and stored in `LastError`. Returns `ErrClosed` after close.

## Identify

```go theme={null}
func (c *Client) Identify(identity Identity) error
```

Queues an identify event for audience insights. It does not change the evaluation context.

**identity.UserID** `string` *required*

A nonempty user ID of at most 256 UTF-16 code units.

`Name` is optional and limited to 256 UTF-16 code units. `Traits` supports at most 100 entries: nonempty keys up to 128 UTF-16 code units, with scalar JSON values or `nil`. Strings are limited to 1024 UTF-16 code units.

**Returns** `nil` after queueing, including when events are disabled.

**Errors.** Invalid identity data or identify events that exceed the payload limit return a validation error. Returns `ErrClosed` after close.

## Flush

```go theme={null}
func (c *Client) Flush(ctx context.Context) error
```

Sends queued evaluation and identify events. The client also flushes automatically every `FlushInterval` and as soon as `FlushAt` events are buffered. The buffer retains at most 200 events; failed batches are requeued, with oldest entries dropped on overflow (see `DroppedEvents`). After a failed delivery, automatic retries wait for the next interval. Evaluation events include values and user IDs; evaluation attributes stay local. Flush splits batches to respect the edge limit of 100 events and 256 KiB per request.

**Returns** `nil` after success, with an empty buffer, or when events are disabled.

**Errors.** Delivery errors are returned and stored in `LastError`. Returns `ErrClosed` after close, including when events are disabled. Use a bounded context for shutdown flushing.

## LastError

```go theme={null}
func (c *Client) LastError() error
```

**Returns** the most recent request failure, or `nil`. A successful refresh or flush, including an empty flush, clears it.

## SnapshotVersion

```go theme={null}
func (c *Client) SnapshotVersion() (version int64, ok bool)
```

**Returns** the loaded snapshot's version. `ok` is `false` until the first valid snapshot arrives. Unlike `Evaluate`, it records no event, so it suits health checks.

## DroppedEvents

```go theme={null}
func (c *Client) DroppedEvents() uint64
```

**Returns** how many events were discarded because the 200-event buffer was full, for example while the edge was unreachable.

## Shutdown

```go theme={null}
func (c *Client) Shutdown(ctx context.Context) error
```

Stops accepting events, attempts to deliver retained pending events within `ctx` (including events from a background flush that is still in progress), then closes the client even if delivery fails. Events already discarded on buffer overflow cannot be delivered; check `DroppedEvents`. Events recorded after `Shutdown` starts are not delivered. Use it for graceful shutdown with a bounded context. Repeated calls are safe.

**Returns** `nil` after events are delivered, or when events are disabled.

**Errors.** Returns the flush error if delivery fails or `ctx` expires. The client is closed either way.

```go theme={null}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := client.Shutdown(ctx); err != nil {
    log.Printf("shipd events: %v", err)
}
```

## Close

```go theme={null}
func (c *Client) Close() error
```

Cancels requests, stops background work, and waits for completion, without delivering pending events; use `Shutdown` to deliver them first. `Close` implements `io.Closer`. Repeated calls are safe.

**Returns** `nil`.

## Errors

| Error | Returned by | Meaning |
| - | - | - |
| `ErrClosed` | `Ready`, `Refresh`, `Flush`, `Identify` | The client was closed. |
| `ErrMalformedSnapshot` | `Refresh`, `Ready`, `New` (with `Bootstrap`) | The snapshot failed validation. The client keeps its last valid snapshot. |
| `ErrUnsupportedSchema` | `Refresh`, `Ready`, `New` (with `Bootstrap`) | The snapshot schema is newer than this SDK. Upgrade the SDK. The message includes both versions. |

Match them with `errors.Is`, because returned errors may wrap them:

```go theme={null}
if errors.Is(client.LastError(), shipd.ErrUnsupportedSchema) {
    log.Print("upgrade the shipd Go SDK")
}
```

**Related:** [Local evaluation](/concepts/local-evaluation) · [Go](/sdks/go)

## Flag definitions

Go flag definitions live in the `github.com/alasti-company/useshipd.com/sdks/go/config` subpackage of the same module. Declare `config.ShipdConfig` directly; the runtime SDK only evaluates flags. See [Go config reference](/reference/config#go-shipdconfig) for its types, validation, export, and defaults methods.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.