Segment analytics-go
repository·v3.0·Indexed 41 days ago
https://github.com/segmentio/analytics-goA Go SDK for sending events to Segment. Supports asynchronous event queuing via Enqueue for track, identify, group, page, screen, and alias calls. Includes a Client interface for managing API connections, a Config struct for batching and retry behavior, and an e2e-cli tool for simulating event sequences. Currently in maintenance mode.
What's inside analytics-go
- This library is currently in maintenance mode. It will continue to send data as intended, but it will not receive new feature support. Only critical maintenance updates will be provided by Segment.
Build the analytics-go e2e-cli
v3.0To build the CLI tool, navigate to the
e2e-clidirectory and use the Go build command. This produces a binary namede2e-cli-bin.cd e2e-cli go build -o e2e-cli-bin ./...Install the Segment analytics-go client
v3.0You can install the Segment analytics client for Go using
go get. It is recommended to use a package version management system (like Go vendor directories) to protect against breaking changes between major versions.go get https://github.com/segmentio/analytics-goRun E2E tests using the provided script
v3.0If you have the
sdk-e2e-testsrepository checked out as a sibling to theanalytics-gorepository, you can userun-e2e.shto build the CLI and run the full test suite.Prerequisites:
- Go 1.17+
- Node.js 18+ (for
run-e2e.sh) sdk-e2e-testsrepo checked out alongside this repo.
# From the e2e-cli directory, with sdk-e2e-tests checked out as a sibling of analytics-go: ./run-e2e.sh # Override the e2e test directory: E2E_TESTS_DIR=/path/to/sdk-e2e-tests ./run-e2e.sh # Pass additional arguments to run-tests.sh: ./run-e2e.sh --suite basicConfigure the SDK via e2e-cli
v3.0You can override SDK configuration using the
configobject in your input JSON.Field Type Description flushAtint Max events per batch (default: 250) flushIntervalint Flush interval in milliseconds maxRetriesint (informational, not directly used by SDK) timeoutint Timeout in seconds (informational) Manage integrations with the Integrations type
v3.0The
Integrationstype is a map used to enable or disable specific integrations (like Salesforce or Marketo) within analytics messages. It is a free-form map where values are typically booleans.To use it, initialize an
Integrationsinstance usingNewIntegrations()and then chain methods to configure your requirements. Any value other thanfalseis interpreted as enabling the integration.analytics.Track{ UserId: "0123456789", Integrations: analytics.NewIntegrations() .EnableAll() .Disable("Salesforce") .Disable("Marketo"), }Extend Context using the Extra map
v3.0If you need to include metadata that is not covered by the standard Segment Spec fields, use the
Extrafield in theContextstruct.Because
Contextimplements thejson.Marshalerinterface, any key-value pairs added to theExtramap will be flattened into the top-level JSON object during serialization. If a key inExtraconflicts with a standard field name, the standard field's value will take precedence.ctx := analytics.Context{ // Standard field Locale: "en-US", // Extension field Extra: map[string]interface{}{ "internal_id": 12345, }, } // Serialized JSON will look like: // { // "locale": "en-US", // "internal_id": 12345 // }Use the analytics-go e2e-cli
v3.0The CLI accepts a JSON description of event sequences via the
--inputflag. It sends these events through the real SDK and reports the result.- stdout: Contains the JSON result.
- stderr: Contains debug and log information.
- Exit Code 0: Success.
- Exit Code 1: Failure.
./e2e-cli-bin --input '<JSON>'Use the Segment analytics-go client
v3.0To use the library, instantiate a client using
analytics.New()with your Segment Write Key. You can then send events asynchronously usingclient.Enqueue(). Finally, callclient.Close()to flush any remaining queued messages and shut down the client gracefully.package main import ( "os" "github.com/segmentio/analytics-go" ) func main() { // Instantiates a client to use send messages to the segment API. client := analytics.New(os.Getenv("SEGMENT_WRITE_KEY")) // Enqueues a track event that will be sent asynchronously. client.Enqueue(analytics.Track{ UserId: "test-user", Event: "test-snippet", }) // Flushes any queued messages and closes the client. client.Close() }Configure the analytics client using Config
v3.0The
Configstruct is used to define the behavior of an analytics client during instantiation. You can customize settings such as the API endpoint, batching behavior, retry logic, and logging. If fields are left at their zero-value, the library applies sensible defaults.Key Configuration Fields
Field Description EndpointThe URL where messages are sent. Defaults to DefaultEndpoint(https://api.segment.io).IntervalHow often the client flushes queued messages. Defaults to DefaultInterval(5 * time.Second).BatchSizeMaximum number of messages per API call. Defaults to DefaultBatchSize(250). Note that the API enforces a 500KB limit per request regardless of this number.TransportAn http.RoundTripperto redefine how requests are sent (e.g., for custom connection pooling). Defaults tohttp.DefaultTransport.LoggerA Loggerimplementation for background operation messages. Defaults to a standard logger writing toos.Stderr.CallbackA Callbackobject used to notify your application when messages succeed or fail.VerboseIf true, the client outputs more frequent and detailed messages to its logger.DefaultContextA *Contextapplied to every message sent by the client.RetryAfterA function func(int) time.Durationthat determines how long to wait before retrying a failed request, based on the retry count.Default Constants
// Example of configuring a client config := analytics.Config{ Endpoint: "https://api.your-custom-endpoint.com", Interval: 10 * time.Second, BatchSize: 500, Verbose: true, }Output JSON format for e2e-cli
v3.0The CLI returns a JSON object indicating the result of the event sequence execution.
On success:
{"success": true, "sentBatches": 1}On failure:
{"success": false, "sentBatches": 0, "error": "description of error"}Input JSON format for e2e-cli
v3.0The input JSON defines the authentication, the sequence of events to simulate, and SDK configuration overrides.
Top-level fields
writeKey(string): Segment write key for authentication.apiHost(string): Full API endpoint URL (e.g.,https://api.segment.io).sequences(array): List of event sequences to run in order.config(object): SDK configuration overrides.
{ "writeKey": "YOUR_WRITE_KEY", "apiHost": "https://api.segment.io", "sequences": [ { "delayMs": 0, "events": [ { "type": "track", "event": "Button Clicked", "userId": "user-123", "properties": { "plan": "pro" } } ] } ], "config": { "flushAt": 15, "flushInterval": 1000, "maxRetries": 3, "timeout": 10 } }