Segment analytics-go

repository·v3.0·Indexed 41 days ago

https://github.com/segmentio/analytics-go

A 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.

Tokens
10.7K
Snippets
49
Records
58
Agent score
50%

What's inside analytics-go

  1. Important maintenance notice for analytics-go

    v3.0
    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.
  2. Install the Segment analytics-go client

    v3.0

    You 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-go
  3. Run E2E tests using the provided script

    v3.0

    If you have the sdk-e2e-tests repository checked out as a sibling to the analytics-go repository, you can use run-e2e.sh to build the CLI and run the full test suite.

    Prerequisites:

    • Go 1.17+
    • Node.js 18+ (for run-e2e.sh)
    • sdk-e2e-tests repo 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 basic
  4. Configure the SDK via e2e-cli

    v3.0

    You can override SDK configuration using the config object in your input JSON.

    FieldTypeDescription
    flushAtintMax events per batch (default: 250)
    flushIntervalintFlush interval in milliseconds
    maxRetriesint(informational, not directly used by SDK)
    timeoutintTimeout in seconds (informational)
  5. Manage integrations with the Integrations type

    v3.0

    The Integrations type 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 Integrations instance using NewIntegrations() and then chain methods to configure your requirements. Any value other than false is interpreted as enabling the integration.

    analytics.Track{
    	UserId:       "0123456789",
    	Integrations: analytics.NewIntegrations()
    		.EnableAll()
    		.Disable("Salesforce")
    		.Disable("Marketo"),
    }
  6. Extend Context using the Extra map

    v3.0

    If you need to include metadata that is not covered by the standard Segment Spec fields, use the Extra field in the Context struct.

    Because Context implements the json.Marshaler interface, any key-value pairs added to the Extra map will be flattened into the top-level JSON object during serialization. If a key in Extra conflicts 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
    // }
  7. Use the analytics-go e2e-cli

    v3.0

    The CLI accepts a JSON description of event sequences via the --input flag. 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>'
  8. Use the Segment analytics-go client

    v3.0

    To use the library, instantiate a client using analytics.New() with your Segment Write Key. You can then send events asynchronously using client.Enqueue(). Finally, call client.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()
    }
  9. Configure the analytics client using Config

    v3.0

    The Config struct 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

    FieldDescription
    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.RoundTripper to redefine how requests are sent (e.g., for custom connection pooling). Defaults to http.DefaultTransport.
    LoggerA Logger implementation for background operation messages. Defaults to a standard logger writing to os.Stderr.
    CallbackA Callback object used to notify your application when messages succeed or fail.
    VerboseIf true, the client outputs more frequent and detailed messages to its logger.
    DefaultContextA *Context applied to every message sent by the client.
    RetryAfterA function func(int) time.Duration that 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,
    }
  10. Input JSON format for e2e-cli

    v3.0

    The 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
      }
    }