Skip to content
FlagSwiftDocs

Go SDK

Standard library only, safe for concurrent use.

Use this SDK in Go services and workers. It downloads your environment's configuration, keeps it fresh and evaluates every flag in memory, so a check costs microseconds and never a network call. For other backends see the Node.js, Python and Java SDKs. Options and behaviour every SDK shares are on Options and behaviour.

At a glance#

Install
go get github.com/flagswift/flagswift-go
Requires
Go 1.21+
Key
Server key (fs_srv_)
Evaluates
Locally, in memory
Real-time updates
Yes
Works offline from
Snapshot file
Outcome analytics
Yes
Verified
Tested against shared vectors

Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.

Installation#

bash
go get github.com/flagswift/flagswift-go

It needs Go 1.21 or newer and has no dependencies beyond the standard library.

Placeholder module path

The module path is a placeholder until the publishing location is decided, and nothing is published yet. Install from the repository for now.

Initialization#

You need a server key (fs_srv_…) or admin key with the evaluation:read scope, and the address of your FlagSwift server. There is no default host. Keep the key on the server and never ship it in a client application. Create one client at startup, call Start, and Close it on shutdown.

main.go
package main

import (
	"context"
	"log"
	"os"

	flagswift "github.com/flagswift/flagswift-go"
)

func main() {
	client, err := flagswift.New(os.Getenv("FLAGSWIFT_KEY"), "https://flags.example.com",
		flagswift.WithEnvironment("production"), // only for project-wide keys
		flagswift.WithFallbacks(map[string]any{"new-checkout": false}),
		flagswift.WithSnapshotPath("/var/cache/myapp/flagswift.json"),
		flagswift.WithOnError(func(err error) { log.Printf("flagswift: %v", err) }),
	)
	if err != nil {
		log.Fatal(err) // a missing key or base URL, not a network problem
	}

	// Waits at most the init timeout (5 seconds) for the first fetch.
	if err := client.Start(context.Background()); err != nil {
		log.Printf("flagswift: starting from snapshot or fallbacks: %v", err) // not fatal
	}
	defer client.Close()
}

Startup never blocks for long

Start returns nil when the init timeout runs out, even with no network. The fetch and poller carry on in the background and apply the configuration as soon as one succeeds.

Connection options#

The API key and base URL are the two arguments of New. Everything else is an option with a default.

Common options of New
OptionTypeDescription
apiKey, baseURL*stringA server or admin key and your server address. A mistake returns an *Error with code MISSING_API_KEY or MISSING_BASE_URL.
WithEnvironment(name)stringOnly for project-wide keys. Default: the FLAGSWIFT_ENVIRONMENT variable.
WithRefreshInterval(d)time.DurationHow often to check for changes. Default 30s. Zero or negative turns polling off.
WithStreaming(bool)boolKeep one real-time connection open so changes arrive within about a second. Default false.
WithFallbacks(map)map[string]anyServed for unknown flags, and before anything loads.
WithSnapshotPath(path)stringFile that keeps the last configuration across restarts.
WithBootstrap(*Payload)*PayloadStart from a payload you saved, so evaluation works before and without the network.
WithTimeout / WithInitTimeouttime.DurationPer request (default 5s) and the longest Start waits (default 5s).
WithMaxRetries(n)intDefault 3. Zero disables retries.
WithAutoExposures(bool)boolQueue an exposure on every single-flag read. Default false.
WithOnError / WithOnUpdatefuncCallbacks for failed refreshes and applied updates. Panics inside them are recovered.
WithHTTPClient(*http.Client)*http.ClientFor proxies or custom TLS.

Check flags#

A User says who is asking. IsEnabled returns false for a flag the server does not know, unless you configured a boolean fallback. IsEnabledOr takes your own default for that case.

go
user := flagswift.User{
	Identifiers: []string{"user-42"},
	Accounts:    []string{"acme"},
	Attributes:  map[string]any{"plan": "pro"},
}

if client.IsEnabled("new-checkout", user) {
	renderNewCheckout()
} else {
	renderOldCheckout()
}

// Use your own default when the flag is not found.
beta := client.IsEnabledOr("beta-banner", user, true)

For the reason behind an answer, call Evaluate. It never fails: an unknown flag gives ReasonFlagNotFound with Found false.

go
ev := client.Evaluate("new-checkout", user)
log.Printf("enabled=%v reason=%s found=%v", ev.Enabled, ev.Reason, ev.Found)

Use it in an HTTP handler#

Build the user from the request and check the flag where you need it. The client is safe to share between goroutines, so pass it in or keep it in a struct.

go
func checkout(client *flagswift.Client) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		user := flagswift.UserID(r.Header.Get("X-User-Id"))
		if !client.IsEnabled("new-checkout", user) {
			http.NotFound(w, r)
			return
		}
		fmt.Fprintln(w, "new checkout")
	}
}

Check variants and values#

A flag can serve a named variant, such as a button colour or a plan limit. Variant gives its key and whether there is one. Value gives what it carries, or the boolean for a plain flag, and falls back to what you pass.

go
if variant, ok := client.Variant("checkout-layout", user); ok && variant == "compact" {
	renderCompact()
}

limit, _ := client.Value("seat-limit", user, 5.0).(float64) // JSON numbers decode as float64

// Every flag at once, for one person.
for key, ev := range client.EvaluateAll(user) {
	log.Println(key, ev.Enabled, ev.Variant)
}

Describe the person#

A User carries Identifiers, Accounts and Devices (all []string) and Attributes (map[string]any). Percentage rollouts bucket on the first identifier. For a person you only know by id, flagswift.UserID(id) builds the user in one call. Attributes feed targeting rules and never leave your server.

Real-time updates#

By default the client polls. Turn on streaming and a flag change reaches your service in about a second. The stream carries only a note that something changed, never flag data, and the client then refetches with its normal conditional request.

go
client, _ := flagswift.New(key, baseURL, flagswift.WithStreaming(true))

While the stream is connected, polling slows to WithStreamingPollInterval (default 5 minutes) as a safety net. If streaming is off on the server or cannot be kept, polling carries on alone. client.Status().Streaming reports off, connecting, connected or unavailable.

Several server instances

A change made on another FlagSwift server instance may not reach your stream. The poll always picks it up, which is why polling never turns off.

Offline and errors#

Once a configuration has loaded, from the server, a snapshot or a bootstrap, evaluation is purely local. It keeps working with no internet and through a FlagSwift outage, and it never returns an error.

What happens when something goes wrong
SituationDescription
A refresh failsThe last good configuration and its ETag stay. The failure is recorded in Status and passed to WithOnError, and polling backs off up to five minutes. The next success resets it.
First load, nothing storedYou get your fallbacks, then false, until the response arrives. Start waits at most the init timeout and returns nil.
Restart during an outageWith WithSnapshotPath the saved file is served from New. The file is written atomically (mode 0600) after every update. A corrupt file, or one from another hashVersion, is ignored.
Bootstrap from your own storageSave client.Snapshot() and pass it to WithBootstrap. The bootstrap wins over the snapshot file.
Server on an unknown hashVersionThe payload is refused rather than silently putting people in the wrong bucket.
Reading the stateclient.Status() has LastError, ErrorCount, ConsecutiveFailures, FlagCount and LastFetch.

Outcome analytics#

Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or turn WithAutoExposures on, and only the person's identifier, the flag, the variant and the event name leave your service.

go
client.TrackExposure("checkout-flow", flagswift.UserID("u_1")) // evaluates locally, queues the outcome this person got
client.Track("purchase", flagswift.UserID("u_1"), 49.90)       // what they did; the value is optional
client.FlushAnalytics(ctx)                                    // send what is queued now and wait

Close flushes what is left on a best-effort basis. See Outcomes for how results are read in the console.

Reference#

Module github.com/flagswift/flagswift-go, package flagswift, Go 1.21 or newer, standard library only. A Client is safe for concurrent use: the configuration is swapped atomically.

Go constructor and options
OptionDescription
New(apiKey, baseURL string, opts ...Option) (*Client, error)Returns an *Error with code MISSING_API_KEY or MISSING_BASE_URL for setup mistakes. Loads a usable bootstrap or snapshot immediately.
WithEnvironment(name)Default: the FLAGSWIFT_ENVIRONMENT variable.
WithRefreshInterval(d)Default 30s. Zero or negative disables polling.
WithTimeout(d)Per request. Default 5s.
WithInitTimeout(d)The longest Start waits. Default 5s.
WithStreaming(bool)Open the real-time stream (see Real-time updates). Default false.
WithStreamingPollInterval(d)While a stream is connected, polling slows to this safety net. Default 5 minutes.
WithMaxRetries(n)Default 3. Zero disables retries.
WithFallbacks(map[string]any)Values for unknown flags, or before anything loads.
WithBootstrap(*Payload)Start from a saved payload, so evaluation works offline.
WithSnapshotPath(path)File read at startup and written after every applied update (JSON, atomic, mode 0600). Bootstrap wins over the file.
WithReportErrors(bool)Default true.
WithOnError(func(error)) / WithOnUpdate(func(*Payload))Callbacks. Panics inside them are recovered.
WithHTTPClient(*http.Client)For proxies or custom TLS.
Go methods
MethodDescription
Start(ctx) errorStarts the poller goroutine and waits up to the init timeout. Returns the first fetch's error if it failed in time, nil if the budget ran out or ctx was cancelled (check Status for an outage). A second call just refreshes.
Close()Cancels the poller and waits for it to exit.
Refresh(ctx) errorFetches now, with If-None-Match. On failure keeps the last config, records it in Status and calls OnError.
Evaluate(flagKey, user User) EvaluationLocal and never fails. Unknown flag: ReasonFlagNotFound and Found false. Nothing loaded: ReasonEnvNotConfigured. A panic is recovered and serves the fallback.
IsEnabled(flagKey, user) boolFalse for unknown flags unless a boolean fallback is configured.
IsEnabledOr(flagKey, user, fallback) boolYour fallback when the flag is not found.
Variant(flagKey, user) (string, bool)The variant key and whether there is one.
Value(flagKey, user, fallback any) anyThe variant value, or the boolean for plain flags. Unknown: the configured fallback, else yours.
EvaluateAll(user) map[string]EvaluationEvery flag.
FlagKeys() []string / Snapshot() *PayloadBoth are nil before anything loads. Pass the snapshot to WithBootstrap.
TrackExposure(flag, user)Evaluates locally and queues the outcome this person got. Unknown flag: ignored. Never fails.
Track(event, user, value...)Records an outcome after the person's pending exposures. The value is optional (the first one is used).
FlushAnalytics(ctx)Sends what is queued now and waits. WithAutoExposures(true) queues an exposure on every single-flag read (default off).
Status() StatusInitialized, Environment, Version, FlagCount, LastFetch, LastError, ErrorCount, ConsecutiveFailures and Streaming (off, connecting, connected or unavailable) and Analytics (Pending, Sent, Dropped, Enabled).
Evaluate, Bucket, IsInRollout, UserIDPackage-level engine functions. UserID(id) builds a User from one identifier.
Go types
TypeDescription
UserIdentifiers, Accounts and Devices ([]string) and Attributes (map[string]any).
Result / EvaluationEnabled, Reason, HasVariant, Variant, Value; Evaluation adds Found.
Reason constantsReasonKillSwitch, ReasonDisabled, ReasonTargetedUser, ReasonSegmentMatch, ReasonRuleMatch, ReasonDependencyBlocked, ReasonFullRollout, ReasonRolloutIn, ReasonRolloutOut, ReasonNoIdentifier, ReasonEnvNotConfigured, ReasonFlagNotFound.
ErrorCode, Status, Message and Retryable. Formats as flagswift: message (code).
Payload, Flag, Config, Rule, ConditionThe configuration shapes. Condition operators are equals, contains and in.