Do NOT embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. If you accidentally expose it, you can create a new one in the Statsig console.
go
import ( statsig "github.com/statsig-io/go-sdk")statsig.Initialize("server-secret-key")// Or, if you want to initialize with certain optionsstatsig.InitializeWithOptions("server-secret-key", &Options{Environment: Environment{Tier: "staging"}})
initialize performs a network request. After initialize completes, virtually all SDK operations are synchronous (refer to Evaluating Feature Gates in the Statsig SDK). The SDK fetches updates from Statsig in the background, independently of API calls.
Working with the SDK
Checking a Feature Flag/Gate
After the SDK is initialized, you can check a Feature Gate. Feature Gates create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (return false;) by default.All APIs require you to specify the user (refer to Statsig user) associated with the request. For example, to check a gate for a user:
go
user := statsig.User{UserID: "some_user_id"}feature := statsig.CheckGate(user, "use_new_feature")if feature { // Gate is on, enable new feature} else { // Gate is off}
Retrieving Feature Gate Metadata
When you need more than a boolean value from a gate evaluation, use the Get Feature Gate API, which returns a FeatureGate object with additional evaluation metadata:
go
user := statsig.User{UserID: "some_user_id"}feature := statsig.GetGate(user, "use_new_feature")if feature.Value { // Gate is on, enable new feature fmt.Print(feature.EvaluationDetails.Reason)}
Reading a Dynamic Config
Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use Dynamic Configs. The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters.
go
config := statsig.GetConfig(user, "awesome_product_details")// The 2nd parameter is the default value to be used in case the given parameter name does not exist on// the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the// value has not been cached on the client.itemName := config.GetString("product_name", "Awesome Product v1");double price = config.GetNumber("price", 10.0);bool shouldDiscount = config.GetBool("discount", false);// Or just get the whole json object backing this config if you preferjson := config.Value
Getting a Layer/Experiment
Use Layers/Experiments to run A/B/n experiments. Two APIs are available, but Statsig recommends layers for faster iterations with parameter reuse.
go
// Values via getLayerlayer := Statsig.GetLayer(user, "user_promo_experiments");promoTitle := layer.GetString("title", "Welcome to Statsig!");discount := layer.GetDouble("discount", 0.1);// or, via getExperimenttitleExperiment := Statsig.GetExperiment(user, "new_user_promo_title");priceExperiment := Statsig.GetExperiment(user, "new_user_promo_price");promoTitle := titleExperiment.GetString("title", "Welcome to Statsig!");discount := priceExperiment.GetNumber("discount", 0.1);...price := msrp * (1 - discount);// getting the layer name that an experiment belongs touserPromoLayer := Statsig.GetExperimentLayer("new_user_promo_title");
Logging an Event
To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object:
For more about identifying users, group analytics, and best practices, go to the logging events guide.
Statsig User
When calling APIs that require a user, pass as much information as possible to take advantage of advanced gate and config conditions (like country or OS/browser level checks), and to correctly measure the impact of your experiments on your metrics/events. At least one identifier (userID or customID) is required to provide a consistent experience for a given user. Refer to userID requirements for more detail.
In addition to userID, email, ip, userAgent, country, locale, and appVersion are available as top-level fields on StatsigUser. You can also pass any key-value pairs in an object/dictionary to the custom field to create targeting based on them.
Typing on the StatsigUser object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but evaluation results for other types are not guaranteed. For example, an array set as a custom field is only compared as a string: there is no operator to match a value within that array.
Private Attributes
To keep sensitive user PII data out of logs, use the privateAttributes field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. Any attribute set in privateAttributes is used only for evaluation/targeting and is removed from all logs before Statsig sends them to its servers.
For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair { email: "my_user@statsig.com" } to privateAttributes on the user.
Statsig Options
initialize() takes an optional options parameter in addition to the secret key to customize the Statsig client. Specify optional parameters when initializing using InitializeWithOptions():
go
type Options struct { API string `json:"api"` Environment Environment `json:"environment"` LocalMode bool `json:"localMode"` ConfigSyncInterval time.Duration IDListSyncInterval time.Duration BootstrapValues string RulesUpdatedCallback func(rules string, time int64)}
Environment: default nil. An object used to set environment variables that apply to all users in the same session, for targeting purposes. The most common use is to set the environment tier (string) so feature gates pass or fail for specific environments. Accepted values are "production", "staging", and "development".
LocalMode: default false. Restricts the SDK to not issue any network requests and only respond with default values (or local overrides).
ConfigSyncInterval: default 10 seconds. The interval for polling gate/experiment/config changes.
IDListSyncInterval: default 1 minute. The interval for polling ID list changes.
BootstrapValues: default nil. A string representing all rules for all feature gates, dynamic configs, and experiments. Provide this to bootstrap the Statsig server SDK at initialization if your server encounters a network issue or Statsig servers are temporarily unavailable.
RulesUpdatedCallback: default nil. A callback invoked whenever the rulesets are updated. Called with a JSON string representing the rulesets and a timestamp for when the rules were updated.
UserPersistentStorage: IUserPersistentStorage, default nil. A persistent storage adapter for running sticky experiments.
DisableIdList: default false. Disables fetching the ID list during initialization and background polling for both network and data adapter.
Client initialize response options
When using getClientInitializeResponse(), you can specify additional options through the GCIROptions struct:
IncludeLocalOverrides: default false. When set to true, the client initialize response includes local overrides. Useful for testing local configuration changes without affecting other users.
ClientKey: default empty string. The client SDK key for the initialize response. This key identifies the client application and determines which configurations it receives. Required when generating a client initialize response for client SDKs.
TargetAppID: default empty string. Filters configurations (feature gates, dynamic configs, experiments, and layers) to those targeted to this application ID. Useful in multi-tenant or multi-application environments. If not specified, the SDK attempts to determine the target app ID from the provided client key.
HashAlgorithm: default empty string. The hashing algorithm used to generate stable IDs in the client. Common values are "djb2" (default if not specified) and "sha256". This should match the hashing algorithm used by the client SDK.
IncludeConfigType: default false (deprecated). When set to true, the response includes the type of each configuration. This option is deprecated and may be removed in a future version.
ConfigTypesToInclude: default empty array. An array of configuration types to include in the response. Possible values include FeatureGateType, DynamicConfigType, ExperimentType, and LayerType. If empty, all configuration types are included (subject to other filtering options).
Shutdown
To gracefully shutdown the SDK and ensure all events are flushed:
go
statsig.Shutdown()
Local Overrides
You can override the values returned by the SDK for testing purposes, which is useful for local development when testing specific scenarios.
go
func OverrideGate(gate string, val bool)func OverrideConfig(config string, val map[string]interface{})
Client SDK bootstrapping
The Statsig server SDK can generate the initialization values for a client SDK. This is useful for server-side rendering (SSR) or when you want to pre-fetch values for a client.
go
user := statsig.User{UserID: "some_user_id"}options := statsig.GCIROptions{}options.ClientKey = "client-YOUR_CLIENT_KEY"result := statsig.GetClientInitializeResponseWithOptions(user, &options)// You can then pass 'result' into a Statsig Client SDK
Data Store
A data store synchronizes configuration/value downloads across multiple SDK instances and bootstraps the SDK in offline environments.
Interface
go
type IDataAdapter interface { /** * Returns the data stored for a specific key */ Get(key string) string /** * Updates data stored for each key */ Set(key string, value string) /** * Startup tasks to run before any get/set calls can be made */ Initialize() /** * Cleanup tasks to run when statsig is shutdown */ Shutdown() /** * Determines whether the SDK should poll for updates from * the data adapter (instead of Statsig network) for the given key */ ShouldBeUsedForQueryingUpdates(key string) bool}
User Persistent Storage is a storage adapter for running sticky experiments that persists user assignments across sessions.
Interface
go
type IUserPersistentStorage interface { /** * Returns the data stored for a specific key */ Load(key string) (string, bool) /** * Updates data stored for a specific key */ Save(key string, data string)}
Example Implementation
go
type userPersistentStorageExample struct { store map[string]string loadCalled int saveCalled int}func (d *userPersistentStorageExample) Load(key string) (string, bool) { d.loadCalled++ val, ok := d.store[key] return val, ok}func (d *userPersistentStorageExample) Save(key string, value string) { d.saveCalled++ d.store[key] = value}
Multi-instance usage
To create multiple independent instances of the Statsig SDK (for example, to use different API keys or configurations), use the instance-based approach:
Use the Local Override APIs in v1.3.0+, in combination with the LocalMode option in StatsigOptions, to force gate/config values in test environments and remove network access to Statsig servers.
For example:
go
c := NewClientWithOptions(secret, &Options{LocalMode: true})user := User{ UserID: "123",}gateDefault := c.CheckGate(user, "any_gate")// "any_gate" is false by defaultc.OverrideGate("any_gate", true)// "any_gate" is now true
// User specific attributes for evaluating Feature Gates, Experiments, and DynamicConfigs//// Learn more why a UserID or a customID is required: /sdks/user#why-is-an-id-always-required-for-server-sdks// PrivateAttributes are only used for user targeting/grouping in feature gates, dynamic configs,// experiments and etc; they are omitted in logs.type User struct { UserID string `json:"userID"` Email string `json:"email,omitempty"` IpAddress string `json:"ip,omitempty"` // Many jurisdictions categorize this as PII; verify whether you should log this. UserAgent string `json:"userAgent,omitempty"` Country string `json:"country,omitempty"` Locale string `json:"locale,omitempty"` AppVersion string `json:"appVersion,omitempty"` Custom map[string]interface{} `json:"custom,omitempty"` PrivateAttributes map[string]interface{} `json:"privateAttributes,omitempty"` StatsigEnvironment map[string]string `json:"statsigEnvironment,omitempty"` CustomIDs map[string]string `json:"customIDs"`}
StatsigOptions
go
// Advanced options for configuring the Statsig SDKtype Options struct { API string `json:"api"` APIOverrides APIOverrides `json:"api_overrides"` Environment Environment `json:"environment"` LocalMode bool `json:"localMode"` ConfigSyncInterval time.Duration IDListSyncInterval time.Duration LoggingInterval time.Duration LoggingMaxBufferSize int BootstrapValues string RulesUpdatedCallback func(rules string, time int64) InitTimeout time.Duration DataAdapter IDataAdapter OutputLoggerOptions OutputLoggerOptions StatsigLoggerOptions StatsigLoggerOptions EvaluationCallbacks EvaluationCallbacks DisableCDN bool // Disables use of CDN for downloading config specs UserPersistentStorage IUserPersistentStorage IPCountryOptions IPCountryOptions UAParserOptions UAParserOptions}type APIOverrides struct { DownloadConfigSpecs string `json:"download_config_specs"` GetIDLists string `json:"get_id_lists"` LogEvent string `json:"log_event"`}type EvaluationCallbacks struct { GateEvaluationCallback func(name string, result bool, exposure *ExposureEvent) ConfigEvaluationCallback func(name string, result DynamicConfig, exposure *ExposureEvent) ExperimentEvaluationCallback func(name string, result DynamicConfig, exposure *ExposureEvent) LayerEvaluationCallback func(name string, param string, result DynamicConfig, exposure *ExposureEvent) ExposureCallback func(name string, exposure *ExposureEvent) IncludeDisabledExposures bool}type OutputLoggerOptions struct { LogCallback func(message string, err error) EnableDebug bool DisableInitDiagnostics bool DisableSyncDiagnostics bool}type StatsigLoggerOptions struct { DisableInitDiagnostics bool DisableSyncDiagnostics bool DisableApiDiagnostics bool DisableAllLogging bool}type IPCountryOptions struct { Disabled bool // Fully disable IP to country lookup LazyLoad bool // Load in background EnsureLoaded bool // Wait until loaded when needed}type UAParserOptions struct { Disabled bool // Fully disable UA parser LazyLoad bool // Load in background EnsureLoaded bool // Wait until loaded when needed}// See /guides/using-environmentstype Environment struct { Tier string `json:"tier"` Params map[string]string `json:"params"`}// options for getClientInitializeResponsetype GCIROptions struct { IncludeLocalOverrides bool ClientKey string HashAlgorithm string //supports "sha256", "djb2", "none", default "sha256"}
Event
go
type Event struct { EventName string `json:"eventName"` User User `json:"user"` Value string `json:"value"` Metadata map[string]string `json:"metadata"` Time int64 `json:"time"`}
FeatureGate
go
type FeatureGate struct { Name string `json:"name"` Value bool `json:"value"` RuleID string `json:"rule_id"` IDType string `json:"id_type"` GroupName string `json:"group_name"` EvaluationDetails *EvaluationDetails `json:"evaluation_details"`}