LiftCanary

SDKs

Go

Server-side decisions for Go services, safe for concurrent use, with live updates and AI config helpers.

liftcanary-go decides on your Go servers: HTTP services, gRPC, workers and CLIs. One client serves every request and is safe for concurrent use. It refreshes the datafile in background goroutines and sends events in batches. A decision is a local function call of well under a microsecond, and it gives a user the same variation as the website, the apps and every other SDK.

Install#

Terminal
go get github.com/liftcanary/liftcanary-go

Go 1.21 or newer. No dependencies: it uses only the standard library.

Usage#

main.go
import liftcanary "github.com/liftcanary/liftcanary-go"

client, err := liftcanary.NewClient(os.Getenv("LIFTCANARY_SDK_KEY"), liftcanary.Options{})
if err != nil {
    log.Fatal(err) // only for an empty key or an invalid Options.Datafile
}

ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
client.Ready(ctx) // at startup; until the first datafile every flag is off
cancel()

http.HandleFunc("/checkout", checkout(client))
A net/http handler
func checkout(lc *liftcanary.Client) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        account := accountFrom(r)
        user := lc.CreateUser(liftcanary.User{
            ID:         account.ID,
            Attributes: map[string]any{"plan": account.Plan, "country": r.Header.Get("CF-IPCountry")},
        })

        flow := user.GetString("new_checkout", "flow", "classic")
        order, err := placeOrder(r.Context(), r.Body, flow)
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }
        user.Track("purchase", liftcanary.TrackOptions{Value: liftcanary.Float64(order.Total)})
        json.NewEncoder(w).Encode(order)
    }
}

The user#

MethodReturns
IsEnabled(flag)Whether the feature is on for this user.
GetString / GetBool / GetFloat / GetInt / GetJSON(flag, name, fallback)The variable, or the fallback when the flag or variable is missing, null or has another type. GetInt only accepts whole numbers.
GetVariable(flag, name, fallback)The same for any JSON kind (numbers are float64).
Decide(flag, ...DecideOption)A Decision: Enabled, VariationKey, RuleKey, InExperiment, Reason, Variables, Revision.
DecideAll()Decisions for every flag, by key.
Track(event, ...TrackOptions)Records a goal event. TrackOptions{Value, Properties}: Value is summed or averaged by goals (revenue, latency).

liftcanary.User{ID, Attributes, BucketingID, Page, ActiveLocations, AnonymousID} takes the same fields as the other SDKs. CreateUser is cheap: call it per request. Attributes are strings, booleans, numbers (any Go numeric type) or nil, and are sent with events; Page (the full request URL, for location conditions) and ActiveLocations never are. Comparisons are type-strict like JavaScript: "10" is not 10, but 10 equals 10.0. Experiment exposures are logged automatically, once per user, flag, rule and variation; pass liftcanary.WithoutExposure() to Decide to skip it, and user.LogExposure(d) to log it later.

At sign-in, pass the browser's anonymous id (the liftcanary_anon cookie, also liftcanary.AnonymousIDCookie) as AnonymousID, so results count the landing-page visit and the signed-in user as one person. The client links the two ids once. BucketingID is optional: set it to the same value only if the server should decide the flag the way the landing page did. See From landing page to app.

Go
var anonymousID string
if cookie, err := r.Cookie(liftcanary.AnonymousIDCookie); err == nil {
    anonymousID = cookie.Value
}
user := client.CreateUser(liftcanary.User{ID: account.ID, AnonymousID: anonymousID})

Options#

Options is a struct; fields left at their zero value use the defaults below.

Datafile
[]byte
Datafile JSON to start from (a file, or //go:embed), so the first decisions need no download.
CDNURL
string
Where datafiles come from. Default https://cdn.liftcanary.com; use your own domain or the API when self-hosting.
EventsURL
string
The collector. Default https://events.liftcanary.com.
DisableStreaming
false
Live updates are on by default; true turns them off and leaves polling.
StreamURL
string
Where live updates connect: {StreamURL}/stream/{sdkKey}. Default: CDNURL.
PollingInterval
30 s
Time between datafile checks, in case the live connection drops (ETag, so unchanged datafiles cost almost nothing). Negative turns polling off; the datafile is still downloaded once at start.
EventFlushInterval
2 s
Time between event sends. Negative sends only full batches, and on Flush and Close.
EventBatchSize
200
Events per request.
EventMaxQueueSize
20000
Events held in memory before the oldest are dropped (counted in client.DroppedEvents()).
HTTPClient
*http.Client
Makes every request (proxies, custom TLS, tests). Requests have their own 10 s timeouts, so leave Timeout unset, or the live connection is cut at that timeout and reconnects.
Logger
*slog.Logger
Receives the SDK's warnings and errors. Without one, nothing is logged.
ModelPrices
map[string]ModelPrice
Price per 1M tokens per model (ModelPrice{Input, Output}), for AI configs.

Live updates#

The client keeps a server-sent events connection open, so a change you publish reaches your decisions in about a second. Polling goes on underneath, so a dropped connection only means waiting for the next poll; reconnects back off from 1 s to 60 s, and a 404 turns live updates off for the life of the client. Only a newer revision is ever applied. client.Subscribe(func()) runs your function after each one and returns a function that unsubscribes.

Shutdown and short jobs#

  • Exit: call client.Close(ctx) when the process stops, after http.Server.Shutdown. It stops the goroutines and sends the remaining events, waiting at most until ctx ends. A deferred Close in main works too, but log.Fatal and os.Exit skip deferred calls.
  • Short jobs and serverless (AWS Lambda, Cloud Functions, CLIs, cron jobs): call client.Flush(ctx) before returning. It returns an error when events are left; they stay queued and are retried.
  • Errors never reach your code: failed downloads are logged to Options.Logger and the last datafile keeps deciding. Event batches are retried with backoff (1 s to 60 s, honouring Retry-After); a 4xx answer other than 429 drops the batch.

AI configs#

Test models, prompts and parameters on real users, measured on latency, tokens, cost, errors and feedback. Your code still calls the provider.

Go
client, err := liftcanary.NewClient(os.Getenv("LIFTCANARY_SDK_KEY"), liftcanary.Options{
    ModelPrices: map[string]liftcanary.ModelPrice{"my-small-model": {Input: 0.25, Output: 1.25}},
})

cfg := liftcanary.GetAIConfig(user, "support_bot", liftcanary.AIConfigFallback{
    Model:  "my-small-model",
    Prompt: "You are a helpful assistant. Answer in {{language}}.",
})
reply, err := liftcanary.MeasureLLM(user, cfg, func() (*Reply, error) {
    system := liftcanary.RenderPrompt(cfg.Prompt, map[string]any{"language": "Turkish"})
    return llm.Chat(r.Context(), cfg.Model, system, messages, cfg.Params)
}, func(res *Reply) liftcanary.LLMTokenUsage {
    return liftcanary.Tokens(res.Usage.InputTokens, res.Usage.OutputTokens)
})

// When the user rates the answer:
liftcanary.TrackFeedback(user, cfg, true)

MeasureLLM is generic over your provider's response type. An error that wraps context.Canceled is recorded as aborted; deadlines count as errors. For streamed answers, MeasureLLMStream(user, cfg) returns a recorder: call Token() on each text chunk (the first one sets the time to first token), Usage(...) when the provider reports tokens, and End(err) once. TrackLLM records a call you measured yourself. Prompts and answers are never sent; see AI configs and LLM experiments.