ABTest SDK for Go
Use the ABTest SDK for Go to implement experiment traffic allocation in your application code and to obtain experiment parameter settings.
Prerequisites
An experiment is created. For more information, see Create an experiment.
Environment variables are configured in the runtime environment of your code. For more information, see Manage access credentials.
Install the ABTest SDK for Go
go get github.com/aliyun/aliyun-pai-ab-go-sdkUsage example
package main
import (
"fmt"
"log"
"os"
"github.com/aliyun/aliyun-pai-ab-go-sdk/api"
"github.com/aliyun/aliyun-pai-ab-go-sdk/experiments"
"github.com/aliyun/aliyun-pai-ab-go-sdk/model"
)
func main() {
// init config
region := "cn-beijing"
accessId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
accessKey := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
config := api.NewConfiguration(region, accessId, accessKey)
// init client
client, err := experiments.NewExperimentClient(config, experiments.WithLogger(experiments.LoggerFunc(log.Printf)))
if err != nil {
log.Fatal(err)
}
// set up experiment context
experimentContext := model.ExperimentContext{
RequestId: "pvid",
Uid: "157",
FilterParams: map[string]interface{}{
"sex": "male",
"age": 35,
},
}
// match experiment
// DefaultProject is project name
experimentResult := client.MatchExperiment("<DefaultProject>", &experimentContext)
// print experiment info
fmt.Println(experimentResult.Info())
// print exp id
fmt.Println(experimentResult.GetExpId())
// get experiment param value
param := experimentResult.GetExperimentParams().GetString("ab_param_name", "not_exist")
if param != "not_exist" {
// experiment logic
} else {
// default logic
}
}Where:
region: the region ID. For example, set it to cn-hangzhou for China (Hangzhou).
request ID: a custom request ID. It is set as a field of the context object in the sample code above.
Uid: the ID used for experiment traffic allocation. It can be a user ID from your service or a device ID.
FilterParams: sex and male are experiment filter parameters. Modify them to match your scenario.
<DefaultProject>: the name of the ABTest project. To view the project name, go to the ABTest project management console page. For more information, see Create an experiment project.