Go Server SDK
Installation
via the go get
CLI:
You can install the latest version of the SDK:
go get github.com/statsig-io/statsig-server-core/statsig-go@latest
or a specific version of the SDK:
go get github.com/statsig-io/statsig-server-core/statsig-go@v0.7.2
Or, add a dependency on the most recent version of the SDK in go.mod:
require (
github.com/statsig-io/statsig-server-core/statsig-go v0.7.2
)
See the Releases tab in GitHub for the latest versions.
Running go get
will only work if you're working inside a module project with a go.mod file. If working outside of a module project, you can clone the repo here: https://github.com/statsig-io/statsig-server-core/tree/main/statsig-go instead.
Run the following commands to install the necessary binaries and set environment variables:
go install github.com/statsig-io/statsig-server-core/statsig-go/cmd/post-install@latest
// Run the following commands based on your OS:
// macOS:
export PATH="$PATH:$(go env GOPATH)/bin"
source ~/.zshrc
// Linux:
export PATH="$PATH:$(go env GOPATH)/bin"
source ~/.bashrc
// Windows (PowerShell):
$env:PATH += ";$env:USERPROFILE\.statsig\bin"
post-install
The system should prompt you to set the environment variables using a statsig.env or statsig.env.ps1 file that was generated during the post-install script. Follow the instructions to set the environment variables.
// E.g. - the command will look something like this:
macOS:
source /Users/Your-User-Name/.statsig_env
Windows (PowerShell):
. "C:\Users\Your-User-Name\.statsig_env.ps1"
Users can also add in the variables to their .bashrc, .zshrc, or .ps1 file to load them automatically.
You may need to have gcc installed on your system in order to run the SDK on Windows.
See FAQ if you run into any issues with installation.
Initialize the SDK
After installation, you will need to initialize the SDK using a Server Secret Key from the Statsig console.
Do NOT embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console.
options
that allows you to pass in a StatsigOptions to customize the SDK.import (
statsig "github.com/statsig-io/statsig-server-core/statsig-go/src"
)
options := statsig.NewStatsigOptionsBuilder().WithOutputLogLevel("DEBUG").Build()
s, err := statsig.NewStatsig("secret-key", *options)
if err != nil {
// Initialize the SDK with the secret key and options
s.Initialize()
}
// Or if you want to initialize the Statsig client with more details
details, err := s.InitializeWithDetails()
json, err := json.MarshalIndent(details, "", " ")
fmt.Println("Initialize With Details:", string(json))
/*
*** Sample Output ***
Initialize With Details: {
"duration": 95,
"init_success": true,
"is_config_spec_ready": true,
"is_id_list_ready": null,
"source": "Network",
"failure_details": null
}
*/
initialize
will perform a network request. After initialize
completes, virtually all SDK operations will be synchronous (See Evaluating Feature Gates in the Statsig SDK). The SDK will fetch updates from Statsig in the background, independently of your API calls.Working with the SDK
Checking a Feature Flag/Gate
Now that your SDK is initialized, let's fetch a Feature Gate. Feature Gates can be used to create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (think return false;
) by default.
From this point on, all APIs will require you to specify the user (see Statsig user) associated with the request. For example, check a gate for a certain user like this:
user := statsig.NewStatsigUserBuilder().WithUserID("a-user").Build()
if s.CheckGate(*user, "a_gate", nil) {
// Gate is on, enable new feature
} else {
// Gate is off
}
Reading a Dynamic Config
Feature Gates can be very useful for simple on/off switches, with optional but advanced user targeting. However, if you want to be able send a different set of values (strings, numbers, and etc.) to your clients based on specific user attributes, e.g. country, Dynamic Configs can help you with that. The API is very similar to Feature Gates, but you get an entire json object you can configure on the server and you can fetch typed parameters from it. For example:
user := statsig.NewStatsigUserBuilder().WithUserID("a-user").Build()
// You can disable exposure logging for this specific check
dynamicConfigOptions := &statsig.GetDynamicConfigOptions{DisableExposureLogging: false}
dynamic_config := "a_config"
config := s.GetDynamicConfig(*user, dynamic_config, dynamicConfigOptions)
// Access the config values
str_val := config.GetString("str_val", "default_str_val") // returns String
int_val := config.GetNumber("number_val", 100) // returns float64
bool_val := config.GetBool("bool_val", false) // returns bool
interface_val := config.GetSlice("interface_val", "default_interface_val") // returns interface{}
map_val := config.GetMap("map_val", "default_map_val") // returns map[string]interface{}
// The config object also provides metadata about the evaluation
fmt.Println(config.RuleID) // The ID of the rule that served this config
fmt.Println(config.IDType) // The type of the evaluation (experiment, config, etc)
Getting a Layer/Experiment
Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but we recommend the use of layers to enable quicker iterations with parameter reuse.
user := statsig.NewStatsigUserBuilder().WithUserID("a-user").Build()
// Getting values with GetExperiment
experimentOptions := &statsig.GetExperimentOptions{DisableExposureLogging: false}
experiment := s.GetExperiment(*user, "a_test_experiment", experimentOptions)
str_val := experiment.GetString("str_val", "default_str_val") // returns String
int_val := experiment.GetNumber("number_val", 100) // returns float64
// Getting values with GetLayer
layerOptions := &statsig.GetLayerOptions{DisableExposureLogging: false}
layer := s.GetLayer(user, "a_test_experiment", layerOptions)
str_val := layer.GetString("str_val", "default_str_val") // returns String
int_val := layer.GetNumber("number_val", 100) // returns float64
Parameter Stores
Sometimes you don't know whether you want a value to be a Feature Gate, Experiment, or Dynamic Config yet. If you want on-the-fly control of that outside of your deployment cycle, you can use Parameter Stores to define a parameter that can be changed into at any point in the Statsig console. Parameter Stores are optional, but parameterizing your application can prove very useful for future flexibility and can even allow non-technical Statsig users to turn parameters into experiments.
Getting a Parameter Store
// Get a Parameter Store by name
s, _ := statsig.NewStatsig("secret-key", options)
user := statsig.NewStatsigUserBuilder().WithUserID("a-user").Build()
options := statsig.ParameterStoreOptions{DisableExposureLogging: false}
paramStore := s.GetParameterStore(*user, "paramStore", &options)
Retrieving Parameter Values
Parameter Store provides methods for retrieving values of different types with fallback defaults.
//String parameters
stringVal := paramStore.GetString("str_param", "default_value")
//Boolean parameters
boolVal := paramStore.GetBoolean("bool_param", false)
//Numeric parameters
intVal := paramStore.GetInt("int_param", 0)
int64Val := paramStore.GetInt64("int64_param", 0)
float64Val := paramStore.GetFloat64("float64_param", 0.0)
//Complex parameters
objectParam := map[string]interface{}{
"value1": "string",
"value2": 1,
"value3": 1.0,
}
objectVal := paramStore.GetMap("obj_param", objectParam)
arrayParam := []interface{}{"val1", "val2", "val3"}
arrayVal := paramStore.GetInterface("array_param", arrayParam)
Evaluation Options
You can disable exposure logging when retrieving a parameter store:
options := statsig.ParameterStoreOptions{DisableExposureLogging: false}
paramStore := s.GetParameterStore(*user, "param_store", &options)
Logging an Event
Now that you have a Feature Gate or an Experiment set up, you may want to track some custom events and see how your new features or different experiment groups affect these events. This is super easy with Statsig—simply call the Log Event API and specify the user and event name to log; you additionally provide some value and/or an object of metadata to be logged together with the event:
event := map[string]interface{}{
"name": "sample event",
"value": "event",
"metadata": map[string]string{
"val_1": "log val 1",
},
}
user := statsig.NewStatsigUserBuilder().WithUserID("a-user").Build()
s.LogEvent(*user, event)
Learn more about identifying users, group analytics, and best practices for logging events in the logging events guide.
Retrieving Feature Gate Metadata
In certain scenarios, you may need more information about a gate evaluation than just a boolean value. For additional metadata about the evaluation, use the Get Feature Gate API, which returns a FeatureGate object:
user := statsig.NewStatsigUserBuilder().WithUserID("a-user").Build()
checkGateOptions := &statsig.CheckGateOptions{DisableExposureLogging: false}
featureGate := s.GetFeatureGate(*user, "a gate", checkGateOptions)
Using Shared Instance
In some applications, you may want to create a single Statsig instance that can be accessed globally throughout your codebase. The shared instance functionality provides a singleton pattern for this purpose:
Manual Exposures
Manually logging exposures can be tricky and may lead to an imbalance in exposure events. For example, only triggering exposures for users in the Test group of an experiment will imbalance the experiment, making it useless.
Manual exposures give you the option to query your gates/experiments without triggering an exposure, and optionally, manually log the exposure after the fact.
- Check Gate
- Get Config
- Get Experiment
- Get Layer
To check a gate without an exposure being logged, call the following.
result = statsig.CheckGate(aUser, "a_gate_name", statsig.CheckGateOptions{DisableExposureLogging: true})
Later, if you would like to expose this gate, you can call the following.
statsig.ManuallyLogGateExposure(aUser, "gate_name")
To get a dynamic config without an exposure being logged, call the following.
config = statsig.GetDynamicConfig(aUser, "config_name", statsig.GetDynamicConfigOptions{DisableExposureLogging: true})
Later, if you would like to expose the dynamic config, you can call the following.
statsig.ManuallyLogDynamicConfigExposure(aUser, "config_name")
To get an experiment without an exposure being logged, call the following.
experiment = statsig.GetExperiment(aUser, "experiment_name", statsig.GetExperimentOptions{DisableExposureLogging: true})
Later, if you would like to expose the experiment, you can call the following.
statsig.ManuallyLogExperimentExposure(aUser, "experiment_name")
To get a layer parameter without an exposure being logged, call the following.
layer = statsig.GetLayer(aUser, "layer_name", statsig.GetLayerOptions{DisableExposureLogging: true})
paramValue = layer.Get(aUser, "param_name")
Later, if you would like to expose the layer parameter, you can call the following.
statsig.ManuallyLogLayerParameterExposure(aUser, "layer_name", "param_name")
Statsig User
When calling APIs that require a user, you should pass as much information as possible in order to take advantage of advanced gate and config conditions (like country or OS/browser level checks), and correctly measure impact of your experiments on your metrics/events. At least one ID (userID or customID) is required because it's needed to provide a consistent experience for a given user (click here)
Besides userID
, we also have email
, ip
, userAgent
, country
, locale
and appVersion
as top-level fields on StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the custom
field and be able to create targeting based on them.
Previous Statsig SDKs enabled country and user agent parsing by default, but our new class of SDKs require you to opt-in by setting StatsigOptions.enable_country_lookup and StatsigOptions.enable_user_agent_parsing. Providing parsed fields yourself is often advantageous for consistency and speed.
While typing is lenient on the StatsigUser
object to allow you to pass in numbers, strings, arrays, objects, and potentially even enums or classes, the evaluation operators will only be able to operate on primitive types - mostly strings and numbers. While we attempt to smartly cast custom field types to match the operator, we cannot guarantee evaluation results for other types. For example, setting an array as a custom field will only ever be compared as a string - there is no operator to match a value in that array.
Private Attributes
Have sensitive user PII data that should not be logged? No problem, we have a solution for it! On the StatsigUser object we also have a field called privateAttributes
, which is a simple object/dictionary that you can use to set private user attributes. Any attribute set in privateAttributes
will only be used for evaluation/targeting, and removed from any logs before they are sent to Statsig server.
For example, if you have feature gates that should only pass for users with emails ending in "@statsig.com", but do not want to log your users' email addresses to Statsig, you can simply add the key-value pair { email: "my_user@statsig.com" }
to privateAttributes
on the user and that's it!
Statsig Options
StatsigOptions Class in Go
The StatsigOptions
class is used to specify optional parameters when initializing the Statsig client.
Parameters
-
SpecsUrl
: Custom URL for fetching feature specifications. -
LogEventUrl
: Custom URL for logging events. -
Environment
: Environment parameter for evaluation. -
EventLoggingFlushIntervalMs
: How often events are flushed to Statsig servers (in milliseconds). -
EventLoggingMaxQueueSize
: Maximum number of events to queue before forcing a flush. -
SpecsSyncIntervalMs
: How often the SDK updates specifications from Statsig servers (in milliseconds). -
OutputLogLevel
: Controls the verbosity of SDK logs. -
DisableCountryLookup
: Disables country lookup based on IP address. Set totrue
to improve performance if country-based targeting is not needed. -
DisableUserAgentParsing
: Disables user agent parsing. Set totrue
to improve performance if device/browser-based targeting is not needed. -
WaitForCountryLookupInit
: Default: falseWhen set to true, the SDK will wait for country lookup data (e.g., GeoIP or YAML files) to fully load during initialization. This may slow down by ~1 second startup but ensures that IP-to-country parsing is ready at evaluation time
-
WaitForUserAgentInit
: Default: falseWhen set to true, the SDK will wait until user agent parsing data is fully loaded during initialization. This may slow down by ~1 second startup but ensures that parsing of the user’s userAgent string into fields like browserName, browserVersion, systemName, systemVersion, and appVersion is ready before any evaluations.
-
DisableAllLogging
: Default: falseWhen set to true, the SDK will not log any events or exposures.
Example Usage
import (
statsig "github.com/statsig-io/statsig-server-core/statsig-go/src"
)
// Initialize StatsigOptions with custom parameters
options := statsig.NewStatsigOptionsBuilder().
WithSpecsUrl("https://example.com/specsUrl").
WithLogEventUrl("https://example.com/logUrl").
WithEnvironment("production").
WithEventLoggingFlushIntervalMs(2000).
WithEventLoggingMaxQueueSize(5000).
WithSpecsSyncIntervalMs(1000).
WithOutputLogLevel("DEBUG").
WithDisableCountryLookup(true).
WithDisableUserAgentParsing(true).
WithWaitForCountryLookupInit(false).
Build()
// Pass the options object when initializing the Statsig client
s, err := statsig.NewStatsig("secret-key", *options)
s.Initialize()
Shutting Statsig Down
Because we batch and periodically flush events, some events may not have been sent when your app/server shuts down.
To make sure all logged events are properly flushed, you should tell Statsig to shutdown when your app/server is closing:
// Method signature
func (s *Statsig) Shutdown() {}
// example usage
s, err := statsig.NewStatsig("secret-key", statsig.StatsigOptions{})
s.Shutdown()
// Method signature
func (s *Statsig) FlushEvents() {}
// example usage
s, err := statsig.NewStatsig("secret-key", statsig.StatsigOptions{})
s.FlushEvents()
Local Overrides
To override the return value of a gate/config/experiment/layer locally, we expose a set of override APIs. Coupling this with StatsigOptions.disable_network can be helpful when writing unit tests.
import (
statsig "github.com/statsig-io/statsig-server-core/statsig-go/src"
)
options := statsig.NewStatsigOptionsBuilder().WithOutputLogLevel("DEBUG").Build()
s, _ := statsig.NewStatsig("secret-key", *options)
s.OverrideLayer("layer_name", map[string]interface{}{"key": "value"}, "test-user-id")
s.OverrideGate("gate_name", true, "test-user-id")
s.OverrideDynamicConfig("config_name", map[string]interface{}{"key": "value"}, "test-user-id")
s.OverrideExperiment("experiment_name", map[string]interface{}{"key": "value"}, "test-user-id")
s.OverrideExperimentByGroupName("experiment_name", "group_name", "test-user-id")
- These only apply locally - they do not update definitions in the Statsig console or elsewhere.
- The local override API is not designed to be a full mock. They are only a convenient way to override the value of the gate/config/etc.
Persistent Storage
The Persistent Storage interface allows you to implement custom storage for experiment assignments. This ensures consistent user experiences across sessions by persisting experiment assignments. For more information on persistent assignments, see the Persistent Assignment documentation.
Data Store
The Data Store interface allows you to implement custom storage for Statsig configurations. This enables advanced caching strategies and integration with your preferred storage systems.
Custom Output Logger
The Output Logger interface allows you to customize how the SDK logs messages. This enables integration with your own logging system and control over log verbosity.
Observability Client
The Observability Client interface allows you to monitor the health of the SDK by integrating with your own observability systems. This enables tracking metrics, errors, and performance data. For more information on the metrics emitted by Statsig SDKs, see the Monitoring documentation.
FAQ
How do I run experiments for logged out users?
See the guide on device level experiments
Installation FAQs
How do I fix undefined symbol errors/linker errors?
You may need to reset your environment variables to those found in the statsig.env or statsig.env.ps1 file which was generated during the post-install script. Running the command sets the environment variables for the current terminal session. Users may need to add in the variables to their .bashrc, .zshrc, or .ps1 file to load them automatically.