Legacy Go Server SDK
Statsig's legacy Server SDK for Go applications; use Go Core for new projects
This is a legacy feature. It is still supported but no longer actively developed; a newer replacement is recommended for new projects.
This page covers the legacy Go SDK. For new implementations, use the Go Core SDK built on the Server Core framework.
Setup the SDK
Install the SDK
Using the
go getCLI:bashgo get github.com/statsig-io/go-sdkOr, add a dependency on the most recent version of the SDK in go.mod:
gorequire ( github.com/statsig-io/go-sdk v1.26.0 )Refer to the Releases tab in GitHub for the latest versions.
Initialize the SDK
After installation, initialize the SDK using a Server Secret Key from the Statsig console.
Don't 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.
goimport ( statsig "github.com/statsig-io/go-sdk" ) statsig.Initialize("server-secret-key") // Or, if you want to initialize with certain options statsig.InitializeWithOptions("server-secret-key", &Options{Environment: Environment{Tier: "staging"}})initializeperforms a network request. Afterinitializecompletes, 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 you initialize the SDK, you can check a Feature Gate. Feature Gates create logic branches in code that you can roll 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:
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:
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.
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 prefer
json := 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.
// Values via getLayer
layer := Statsig.GetLayer(user, "user_promo_experiments");
promoTitle := layer.GetString("title", "Welcome to Statsig!");
discount := layer.GetDouble("discount", 0.1);
// or, via getExperiment
titleExperiment := 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 to
userPromoLayer := 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:
statsig.LogEvent(Event{
User: user,
EventName: "add_to_cart",
Value: "SKU_12345",
Metadata: map[string]string{"price": "9.99","item_name": "diet_coke_48_pack"},
})
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. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to userID requirements for more detail.
In addition to userID, the top-level fields on StatsigUser are email, ip, userAgent, country, locale, and appVersion. 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 Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's 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. The SDK uses any attribute set in privateAttributes only for evaluation/targeting and removes it 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():
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 update. 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:
type GCIROptions struct {
IncludeLocalOverrides bool
ClientKey string
TargetAppID string
HashAlgorithm string
IncludeConfigType bool
ConfigTypesToInclude []ConfigType
}
- 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 the client SDK uses.
- IncludeConfigType: default false (deprecated). When set to true, the response includes the type of each configuration. This option is deprecated, and Statsig may remove it 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, the response includes all configuration types (subject to other filtering options).
Shutdown
To gracefully shutdown the SDK and flush all events:
statsig.Shutdown()
Local Overrides
You can override the values the SDK returns for testing purposes, which is useful for local development when testing specific scenarios.
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.
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
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
}
Example Implementation
type dataAdapterExample struct {
store map[string]string
mu sync.RWMutex
}
func (d *dataAdapterExample) Get(key string) string {
d.mu.RLock()
defer d.mu.RUnlock()
return d.store[key]
}
func (d *dataAdapterExample) Set(key string, value string) {
d.mu.Lock()
defer d.mu.Unlock()
d.store[key] = value
}
func (d *dataAdapterExample) Initialize() {}
func (d *dataAdapterExample) Shutdown() {}
func (d *dataAdapterExample) ShouldBeUsedForQueryingUpdates(key string) bool {
return false
}
User persistent storage
User Persistent Storage is a storage adapter for running sticky experiments that persists user assignments across sessions.
Interface
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
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:
sdkInstance := NewClientWithOptions(sdkKey, &Options{})
FAQ
How do I run experiments for logged out users
Refer to the guide on device level experiments.
How can I mock Statsig in tests
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:
c := NewClientWithOptions(secret, &Options{LocalMode: true})
user := User{
UserID: "123",
}
gateDefault := c.CheckGate(user, "any_gate")
// "any_gate" is false by default
c.OverrideGate("any_gate", true)
// "any_gate" is now true
Refer to https://github.com/statsig-io/go-sdk/blob/main/overrides_test.go
Reference
StatsigUser
// 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
// Advanced options for configuring the Statsig SDK
type 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-environments
type Environment struct {
Tier string `json:"tier"`
Params map[string]string `json:"params"`
}
// options for getClientInitializeResponse
type GCIROptions struct {
IncludeLocalOverrides bool
ClientKey string
HashAlgorithm string //supports "sha256", "djb2", "none", default "sha256"
}
Event
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
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"`
}
DynamicConfig
type DynamicConfig struct {
Name string `json:"name"`
Value map[string]interface{} `json:"value"`
RuleID string `json:"rule_id"`
IDType string `json:"id_type"`
GroupName string `json:"group_name"`
EvaluationDetails *EvaluationDetails `json:"evaluation_details"`
AllocatedExperimentName string `json:"allocated_experiment_name"`
GetString(key string, fallback string) string
GetNumber(key string, fallback float64) float64
GetBool(key string, fallback bool) bool
GetSlice(key string, fallback []interface{}) []interface{}
GetMap(key string, fallback map[string]interface{}) map[string]interface{}
}
Was this helpful?