Introduction

SDK overview

Welcome to the Flagship Go SDK documentation!

The following documentation will help you get Flagship running in your Go environment (server-side) with preconfigured methods to implement the Decision API & Bucketing.

Feel free to contact us if you have any questions regarding this documentation.

SDK features

That SDK version helps you :

Prerequisites

  • This SDK requires Go 1.12 version or later to work
  • Your server/device must have an access to the internet.

Good to know

Getting Started

Installation

Follow these steps to install the Go SDK

Install from github

To install from github, just run a go get to add the SDK to your GOPATH

go get github.com/abtasty/flagship-go-sdk/v2

Install from source

To install from github, just run a go get to add the SDK to your GOPATH,
and run a go install to add the library to your installed dependencies.

go get github.com/abtasty/flagship-go-sdk/v2

cd $GOPATH/src/github.com/abtasty/flagship-go-sdk

go install

Install using go.mod

Add the Flaship SDK dependency to your go.mod file and

module mymodule

go 1.12

require (
	github.com/abtasty/flagship-go-sdk/v2 v2.0.2
)

If you are already using go.mod in your application you can run the following:

go mod edit -require github.com/abtasty/flagship-go-sdk/[email protected]

Initialization

Environment ID

You can find your environment id in the parameters\integration section of your Flagship account. (Check Getting Started)

// Using the Decision API (default)
fsClient, err := flagship.Start(environmentID, apiKey)

// Using the Bucketing mode
fsClient, err := flagship.Start(environmentID, apiKey, client.WithBucketing())

To initialize and start the library, just call the Start function of the flagship package,
using the bucketing function builder if you want to use the bucketing mode

The start function return a Flagship client instance for your environment.

ParameterTypeDescription
envIdstringEnvironment id provided by Flagship.
apiKeystringApi authentication key provided by Flagship.
optionBuildersVariadic functionsOption builder functions.

📘

You can find your apiKey and your environmentId on your Flagship account, in Parameters > Environment & Security. Find this ID

Decision Mode

DECISION_API Mode

When the SDK is running in DECISION_API mode, the campaign assignments and targeting validation take place server-side.
In this mode, each call to the SynchronizeModifications method to refresh the modifications will create an HTTP request.

BUCKETING Mode

When the SDK is running in BUCKETING mode, the SDK downloads all the campaigns configurations at once in a single bucketing file so that variation assignment can be computed client-side by the SDK.
This bucketing file is stored in cache and will only be downloaded again when campaign configurations are modified in the Flagship interface.
It is possible to configure the interval of polling refresh with the PollingInterval configuration builder. Learn more

Options

func decision.WithDecisionAPI(...apiOptionBuilder): Builder

Start Flagship SDK in DECISION API mode (which is the default).
apiOptionBuilders functions allows you to customize the API engine.

ParameterTypeDescription
apiOptionBuildersVariadic functionsoption builder for the Bucketing.

func decisionapi.Timeout((timeout time.Duration)

API Option builder that sets the Decision API URL for the DECISION API mode.
Useful to prevent the Decision API calls from having performance impacts on your app.
If the Decision API call throws a timeout, then default modification values will be returned when calling GetModifications.

ParameterTypeDescription
timeouttime.DurationThe Decision API call timeout

func WithBucketing(...bucketingOptionBuilder)

Start Flagship SDK in BUCKETING mode (client-side) instead of DECISION API mode.
bucketingOptionBuilder functions allows you to customize the bucketing engine.

ParameterTypeDescription
bucketingOptionBuildersVariadic functionsoption builder for the Bucketing.

func PollingInterval(interval time.Duration)

Set the polling interval for the bucketing engine (set by default to 60 seconds).

ParameterTypeDescription
intervaltime.DurationThe polling interval for the bucketing.

Create a visitor

The SDK provides a method create a new visitor with an ID and a context.

The context is a property dataset which defines the current user of your app. This dataset is sent and used by the Flagship decision API as targeting for campaign allocation. For example, you could pass a VIP status in the context and then the decision API would enable or disable a specific feature flag.

📘

Visitor context values are used to match a visitor to the targeting of a campaign

📘

Visitor context values type must be:

  • string
  • Number (int or float64)
  • bool
// Create visitor context
context := map[string]interface{}{
  "isVip": true,
  "age": 30,
  "name": "visitor",
}
// Create a visitor
fsVisitor, err := fsClient.NewVisitor("visitor_id", context)

The NewVisitor function takes the following parameters:

ParameterTypeDescription
VisitorIDstringThe ID of the visitor (must be unique for a visitor)
Contextmap[string]interface{}The context of the visitor. It should match those defined in your campaigns to target your users on it.
visitorOptionsVariadic functionsOption builder functions.

Visitor Options

func decision.WithAuthenticated(isAuthenticated bool)

Specify if the visitor starts as authenticated or anonymous, if you plan on using the Experience Continuity

ParameterTypeDescription
isAuthenticatedboolShould the visitor ID be authenticated or anonymous

Updating the visitor Context

The visitor context can be updated in case some context linked to your visitor has changed.
The SDK provides 2 methods to change the visitor context:

  • Either change a single key of the context
  • Or replace the whole context with a new one
// Update a single key
fsVisitor.UpdateContextKey("vipUser", true)
fsVisitor.UpdateContextLey("age", 30)

// Update the whole context
newContext := map[string]interface{}{
  "isVip": true,
  "age": 30,
  "name": "visitor",
}
fsVisitor.UpdateContext(newContext)

UpdateContextKey(key string, value interface{})

This functions update the visitor context value matching the given key.
A new context value associated with this key will be created if there is no previous matching value.

ParameterTypeDescription
keystringkey to associate with the following value
valueinterface{}new context value

UpdateContext(newContext map[string]interface{})

ParameterTypeDescription
newContextmap[string]interface{}key to associate with the following value

📘

Visitor context values type must be:

  • string
  • Number (int or float64)
  • bool

Campaign synchronization

Synchronizing campaigns

Synchronizing campaign modifications allows you to automatically call the Flagship decision API (or bucketing file), which makes the allocation according to user context and gets all their modifications.

All the applicable modifications are stored in the SDK and are updated synchronously when SynchronizeModifications() is called.

This function has no parameters

fsVisitor.SynchronizeModifications()

🚧

SynchronizeModifications must be called before trying to get a modification value

Getting modifications

Once the campaign has been allocated and synchronized all the modifications are stored in the SDK. Then, you can retrieve them with the following functions:

discountName, err := fsVisitor.GetModificationstring("discountName", "Black Friday", true);

// If there is not error (and if there is, your value will still be set to defaut), you can use your modification value in your business logic
discountValue := getDiscountFromDB(discountName)
  • Get Modification for Number value:

    func (v *FlagshipVisitor) GetModificationNumber(key string, defaultValue float64, activate bool) (castVal float64, err error)

  • Get Modification for String value:

    func (v *FlagshipVisitor) GetModificationString(key string, defaultValue string, activate bool) (castVal string, err error)

  • Get Modification for Boolean value:

    func (v *FlagshipVisitor) GetModificationBool(key string, defaultValue bool, activate bool) (castVal bool, err error)

  • Get Modification for Object value:

    func (v *FlagshipVisitor) GetModificationBool(key string, defaultValue map[string]interface{}, activate bool) (castVal map[string]interface{}, err error)

  • Get Modification for Array value:

    func (v *FlagshipVisitor) GetModificationBool(key string, defaultValue []interface{}, activate bool) (castVal []interface{}, err error)

ParameterTypeRequiredDescription
keystringYeskey associated to the modification.
defaultValuestring, bool, float64, map[string]interface{}, []interface{}Yesdefault value returned when the key doesn't match any modification value.
activatebool Nofalse by default Set this parameter to true to automatically report on our server that the current visitor has seen this modification. If false, call the activateModification() later.

Getting campaign information

You may need to send campaign IDs to a third-party for reporting and/or analytics purposes. It is now possible to retrieve campaign IDs for a specific modification key.

infos, err := fsVisitor.GetModificationInfo("visitor_id")

func (v *Visitor) GetModificationInfo(key string) (modifInfo *ModificationInfo, err error)

ParameterTypeDescription
keystrKey associated with the modification.

It returns a struct containing CampaignId, VariationGroupID, VariationID, Value (modification key value), or nil if the modification is not found (i.e. user does not belong to the campaign).

Activating modifications

Once a modification has been printed on the screen for a user, you must send an activation event to tell Flagship that the user has seen this specific variation.

// Activate the modification automatically when retrieving it
color, err := Flagship.GetModificationString("discountName", "Black Friday", true)

// ---OR---

// Activate the modification later on manually
err := Flagship.ActivateModification("discountName")

func (v *FlagshipVisitor) ActivateModification(key string)

ParameterTypeDescription
keyStringkey which identifies the modification

Experience Continuity

Dealing with anonymous and logged-in users, experience continuity allows you to maintain consistency between sessions and devices.

🚧

Make sure that the experience continuity option is enabled on the flagship platform before using those methods.

Authenticate

func authenticate(newID string, newContext map[string]interface{}, sync bool)

ParameterTypeDescription
newIDstringnew ID of the new authenticated visitor.
newContextmap[string]interface{}(optional) Replace the current visitor context. Passing nil wont replace context and will insure consistency with the previous visitor context.
syncboolif true, the SDK will automatically update the campaigns modifications. You also have the possibility to update it manually by calling synchronizeModifications()

Unauthenticate

func unauthenticate(newContext map[string]interface{}, sync bool)

ParameterTypeDescription
newContextmap[string]interface{}(optional) Replace the current visitor context. Passing nil wont replace context and will insure consistency with the previous visitor context.
syncboolif true, the SDK will automatically update the campaigns modifications. You also have the possibility to update it manually by calling synchronizeModifications()

Example code

// Your visitor logs in
user := getUser(session)

// Update the new context with your user data
newContext := map[string]interface{}{
  "session_id": session.ID,
  "age": user.Age,
  "name": user.Name,
}

// Updates the Flagship visitor ID, the new context and resynchronize campaigns
err := fsVisitor.Authenticate("logged_in_id", newContext, true)

// Get the new modification value when retrieving it
discountName, err := Flagship.GetModificationString("discountName", "Black Friday", true)

// Use your modification inside your code
price := getPrice(discountName)

// ...
// Then later on, when your visitor logs out, you can unauthenticate the visitor
// and clear the context
newContext = map[string]interface{}{
  "session_id": "sessionID",
}
err := fsVisitor.Unauthenticate(newContext, true)

Hit Tracking

This section helps send tracking and learn how to build hits in order to aprove campaign goals.

The different types of Hits are:

They must all be built and sent with the following function:

func (v *FlagshipVisitor) SendHit(hit model.HitInterface) (err error)

Common parameters

These parameters can be sent with any type of hit.


ParameterTypeDescription
UserIPStringoptional User IP
ScreenResolutionStringoptional Screen Resolution.
UserLanguageStringoptional User Language
CurrentSessionTimeStampInt64optional Current Session Timestamp
SessionNumberIntoptional Session Number

Hit types

Page

fsVisitor.SendHit(&model.PageHit{
  DocumentLocation: "http://localhost:8080",
})

This hit should be sent each time a visitor arrives on a new interface.

Hit parameterTypeRequiredDescription
DocumentLocationStringYesURL of the page, must be a valid URL

Screen

fsVisitor.SendHit(&model.ScreenHit{
  DocumentLocation: "My page name",
})

This hit should be sent each time a visitor arrives on a new interface.

Hit parameterTypeRequiredDescription
DocumentLocationStringYesName of the page

Transaction

This hit should be sent when a user complete a Transaction.

fsVisitor.SendHit(&model.TransactionHit{
  TransactionID: "YOUR_TRANSACTION_ID",
  Affiliation: "GOAL_NAME", // The goal name set in Flagship campaign
  Revenue: 100,
  Shipping: 10,
  Tax: 5,
  Currency: "EUR",
  CouponCode: "discount",
  PaymentMethod: "Card",
  ShippingMethod: "postal",
  ItemCount: 2,
})
Hit ParameterTypeRequiredDescription
TransactionIdStringYesTransaction unique identifier.
AffiliationStringYesTransaction name. Name of the goal in the reporting.
RevenueFloat64NoTotal revenue associated with the transaction. This value should include any shipping or tax costs.
ShippingFloat64NoSpecifies the total shipping cost of the transaction.
ShippingMethodStringNoSpecifies the shipping method of the transaction.
TaxFloat64NoSpecifies the total taxes of the transaction.
CurrencyStringNoSpecifies the currency used for all transaction currency values. Value should be a valid ISO 4217 currency code.
PaymentMethodStringNoSpecifies the payment method for the transaction.
ItemCountIntNoSpecifies the number of items for the transaction.
CouponCodeStringNoSpecifies the coupon code used by the customer for the transaction.

Item

fsVisitor.SendHit(&model.ItemHit{
  TransactionID: "YOUR_TRANSACTION_ID", // Must be the same as for the Transaction Hit
  Name: "t-shirt",
  Category: "Clothes",
  Code: "SN123456",
  Quantity: 5,
  Price: 25.4,
})

This hit is linked to a transaction. It must be send after the corresponding transaction.

class Item(transactionId: String, productName: String) : HitBuilder<Item>()

Hit ParameterTypeRequired Description
TransactionIdStringYesTransaction unique identifier.
NameStringYesProduct name.
PriceFloat64NoSpecifies the item price.
CodeStringYesSpecifies the item code or SKU.
CategoryStringNoSpecifies the item category.
QuantityIntNoSpecifies the item quantity

❗️

The Item hit isn't available yet in the Flagship reporting view.

Event

fsVisitor.SendHit(&model.EventHit{
  Action: "GOAL_NAME", // The event goal name set in the Flagship campaign
  Category: "Action Tracking",
  Label: "Event label",
  Value: 5,
})

This hit can be anything you want: for example a click or a newsletter subscription.

Hit ParameterTypeRequired Description
CategoryStringYescategory of the event ("Action Tracking" or "User Engagement").
ActionStringYesthe event action.
LabelStringNolabel of the event.
ValueNumberNoSpecifies a value for this event. must be non-negative.

Appendix

Implementation sample

// Start SDK
fsClient, _ := flagship.Start(ENVIRONMENT_ID, API_KEY)
// if err != nil

// Create a visitor
fsVisitor, _ := fsClient.NewVisitor("visitor_123", nil)
// if err != nil

// Update context to target visitors & synchronize
_ = fsVisitor.UpdateContext(map[string]interface{}{
	"vip": true,
})
// if err != nil
fsVisitor.SynchronizeModifications()

featureTitle, _ := fsVisitor.GetModificationString("feature_title", "default_title", false)
_ = fsVisitor.ActivateModification("feature_title")

fmt.Println("featureTitle", featureTitle)

// Send hit
fsVisitor.SendHit(&model.EventHit{
	Action: "feature_click",
})

API reference

https://godoc.org/github.com/abtasty/flagship-go-sdk