# Go Source Library

## How it works[](#how-it-works)

Our Go library helps you record source events from your server-side code. This lets your Go-based app send requests to our servers, and we route your data to your cloud-mode destinations.

Like our other libraries, you can log anonymous activity with an `anonymousId`. When you `identify` a person, you can pass the `anonymousId` and we’ll associate the anonymous activity with the identified person.

This library uses a configurable buffer to batch messages, optimized to reduce network activity.

## Getting Started[](#getting-started)

1.  Go to the tab and click **Sources**.
    
2.  Click **Add Source** and pick **Go**.
    
3.  Give the source a *Name* and click **Complete Setup**. The name is simply a friendly name to help you find and recognize your source in Customer.io.
    
4.  Install `analytics-go` using `go get`:
    
    ```bash
    go get github.com/customerio/cdp-analytics-go
    ```
    
5.  Import the library and initialize an instance with your source’s **API Key**. You’ll find your key in your source’s **Settings** tab. You can initialize the library with configuration settings—like using our [EU data center](#eu-data-center) or [development settings](#development) to help you test your implementation.
    
    ```go
     package main
    
     import (
       "github.com/customerio/cdp-analytics-go"
     )
    
     func main() {
       client := analytics.NewWithConfig("YOUR_API_KEY", analytics.Config{
         // Set config options here
         // If you're in our EU data center, set Endpoint:
         // Endpoint: "https://cdp-eu.customer.io",
       })
    
       // Flush queued messages and close the client.
       defer client.Close()
     }
    ```
    
    This creates a `client` that you can use to send data to Customer.io. The client uses our default, production settings but you can tune these settings to fit your need. While you develop your integration, you may want to use [development settings](#development) so it’s easier to test and debug your work!
    

Now you’re ready to send requests to Customer.io. Check out our [Pipelines API reference](/integrations/api/cdp/), or read further to see example requests and understand the types of requests you can make using our Go library.

### If you’re in our EU data center[](#eu-data-center)

You’ll need to update your config to use our EU endpoint. Note that this accounts for the location of your data in Customer.io; it doesn’t account for the locations of your sources and destinations.

```go
func main() {
  client, err := analytics.NewWithConfig("YOUR_API_KEY", analytics.Config{
    Endpoint: "https://cdp-eu.customer.io",
  })
  // use the SDK here

  // Flush queued messages and close the client.
  defer client.Close()
}
```

### Enable automatic geolocation support[](#enable-automatic-geolocation-support)

You can automatically geolocate people when you identify them and pass their IP addresses in the `context.ip` field in your `identify` requests. This helps you gather information about your audience’s location and time zone so you can schedule messages at the right times or send messages relevant to their communities.

If you’ve already set up your integration to capture IP addresses, and you’ve enabled the workspace-level [Automatic Geolocation Data Collection](/journeys/geolocation-data/#enable-or-disable-automatic-geolocation-data-collection) setting, you can enable geolocation for your integration.

**After you set up your integration**, go to your integration’s **Settings** tab and turn on the **Enable Geolocation** setting.

[![settings for a server-side integration showing the Enable Geolocation setting](https://docs.customer.io/images/automatic-geolocation-server.png)](#e920e572d15951c4f5191f022724e78d-lightbox)

 Make sure you capture your users’ IP addresses

If you don’t set the `context.ip` in your requests, we won’t be able to capture geolocation data for your users. If our libraries infer the address as your server’s IP address, it’ll look like everyone is in the same location as your server.

## Identify[](#identify)

The `identify` method tells us who the current website visitor is, and lets you assign unique [traitsA key-value pair that you associate with a person or an object—like a person’s name, the date they were created in your workspace, or a company’s billing date etc. Use attributes to target people and personalize messages.](/journeys/attributes/) to a person.

You should call `identify` when a user creates an account, logs in, etc. You can also call it again whenever a person’s traits change. We’ve shown a typical call with a `traits` object, but we’ve listed all the fields available in an `identify` call below.

You can send an identify call with an `anonymousId` and/or `userId`.

*   **`anonymousId` only**: This assigns traits to a person before you know who they are.
*   **`userId` only**: Identifies a user and sets traits.
*   **both `userId` and `anonymousId`**: Associates the data sent in previous anonymous `page`, `track`, and `identify` calls with the person you identify by `userId`.

```go
client.Enqueue(analytics.Identify{
  UserId: "019mr8mf4r",
  Traits: analytics.NewTraits().
    SetName("Cool Person").
    SetEmail("cool.person@example.com").
    Set("plan", "Enterprise").
    Set("fav_number", 42),
})
```

*   integrations object
    
    Contains a list of booleans indicating the integrations that are enabled (true) or disabled (false). By default, all integrations are enabled (returning an empty object). Set `"All": false` to reverse this behavior.
    
    *   *Enabled/Disabled integrations\** boolean
        
*   timestamp string  (date-time)
    
    The ISO-8601 timestamp when the event originally took place. This is mostly useful when you backfill data past events. If you’re not backfilling data, you can leave this field empty and we’ll use the current time or server time.
    
*   traits object
    
    Additional properties that you know about a person. We’ve listed some common/reserved traits below, but you can add any traits that you might use in another system.
    
    *   createdAt string  (date-time)
        
        We recommend that you pass date-time values as ISO 8601 date-time strings. We convert this value to fit destinations where appropriate.
        
    *   email string
        
        A person’s email address. In some cases, you can pass an empty `userId` and we’ll use this value to identify a person.
        
    *   *Additional Traits\** any type
        
        Traits that you want to set on a person. These can take any JSON shape.
        

## Track[](#track)

The `track` method tells us about actions people take—the events people perform—on your site. Every `track` call represents an *event*.

You should track your audience’s activities with events both as performance indicators *and* so you can respond to your audience’s activities with [campaignsCampaigns are automated workflows you set up to send people messages and perform other actions when they meet your criteria.](/journeys/campaigns-in-customerio/) in Journeys. For example, if your audience performs a **Video Viewed** or **Item Purchased** event, you might respond with other videos or products the person might enjoy.

You can send events with an `anonymousId` or a `userId`. Calls that you make with an `anonymousId` are associated with a `userId` when you `identify` someone by their `userId`.

Track calls require an `event` name describing what a person did. And they generally include a series of `properties`, providing additional information about the event. Beyond that, we’ve provided a complete schema for writable event fields below, and you can find more information in our [API documentation](/integrations/api/cdp/#operation/track).

 track with userId

#### track with userId[](#track with userId)

```go
client.Enqueue(analytics.Track{
  UserId: "f4ca124298",
  Event:  "added_to_cart",
  Properties: analytics.NewProperties().
    Set("product", "shoes"),
    Set("price", 39.95),
})
```

 track with anonymousId

#### track with anonymousId[](#track with anonymousId)

```go
client.Enqueue(analytics.Track{
  anonymousId: "48d213bb-95c3-4f8d-af97-86b2b404dcfe",
  Event:  "added_to_cart",
  Properties: analytics.NewProperties().
    Set("product", "shoes"),
    Set("price", 39.95),
})
```

*   event string
    
    Required The name of the event
    
*   integrations object
    
    Contains a list of booleans indicating the integrations that are enabled (true) or disabled (false). By default, all integrations are enabled (returning an empty object). Set `"All": false` to reverse this behavior.
    
    *   *Enabled/Disabled integrations\** boolean
        
*   properties object
    
    Additional properties for your event.
    
    *   *Event Properties\** any type
        
        Additional properties that you want to capture in the event. These can take any JSON shape.
        
*   timestamp string  (date-time)
    
    The ISO-8601 timestamp when the event originally took place. This is mostly useful when you backfill data past events. If you’re not backfilling data, you can leave this field empty and we’ll use the current time or server time.
    

*   event string
    
    Required The name of the event
    
*   integrations object
    
    Contains a list of booleans indicating the integrations that are enabled (true) or disabled (false). By default, all integrations are enabled (returning an empty object). Set `"All": false` to reverse this behavior.
    
    *   *Enabled/Disabled integrations\** boolean
        
*   properties object
    
    Additional properties for your event.
    
    *   *Event Properties\** any type
        
        Additional properties that you want to capture in the event. These can take any JSON shape.
        
*   timestamp string  (date-time)
    
    The ISO-8601 timestamp when the event originally took place. This is mostly useful when you backfill data past events. If you’re not backfilling data, you can leave this field empty and we’ll use the current time or server time.
    

### Deduplicate events[](#deduplicate-events)

By default, we automatically assign a `messageId` to each call you make to Customer.io. But, you can set your own `messageId` if you need to deduplicate calls to Customer.io, ensuring that you don’t bog down your workspace with unnecessary traffic or trigger unnecessary downstream actions.

We’ll accept the first instance of any operation with a given `messageId` and ignore any operations with the same `messageId` **for the next 12 hours**. The `messageId` is can be any string value, but we recommend a hash of the event data or a UUID/ULID to ensure that you don’t inadvertently deduplicate events.

If you [backdate events](/integrations/data-in/importing-old-data/#advanced-backfilling-events), you’ll need to deduplicate them before you send them to Customer.io. We deduplicate the `messageId` for 12 hours after we receive the operation—not the timestamp on the event itself.

```go
client.Enqueue(analytics.Track{
  UserId: "f4ca124298",
  Event:  "added_to_cart",
  Properties: analytics.NewProperties().
    Set("product", "shoes").
    Set("price", 39.95),
  MessageId: "message_id_here",
})
```

## Page[](#page)

The [Page](/integrations/api/cdp/#operation/page) method records page views on your website, along with optional extra information about the page a person visited.

If you’re using Customer.io’s client-side set up in combination with the Go library, page calls are already tracked for you by default on any page that loads the client-side script.

But, if you have a single page app or you *don’t* use our JavaScript client library on your website, you’ll need to send your own page calls.

```go
client.Enqueue(analytics.Page{
  UserId: "f4ca124298",
  Name:   "Customer.io CDP",
  Category: "Docs",
  Properties: analytics.NewProperties().
    SetURL("https://customer.io/cdp/"),
})
```

*   integrations object
    
    Contains a list of booleans indicating the integrations that are enabled (true) or disabled (false). By default, all integrations are enabled (returning an empty object). Set `"All": false` to reverse this behavior.
    
    *   *Enabled/Disabled integrations\** boolean
        
*   name string
    
    Required The name of the page.
    
*   properties object
    
    Additional properties for your event.
    
    *   category string
        
        The category of the page. This might be useful if you have a single page routes or have a flattened URL structure.
        
    *   *Page Properties\** any type
        
        Additional properties tha tyou want to send with the page event. By default, we capture \`url\`, \`title\`, and stuff.
        
*   timestamp string  (date-time)
    
    The ISO-8601 timestamp when the event originally took place. This is mostly useful when you backfill data past events. If you’re not backfilling data, you can leave this field empty and we’ll use the current time or server time.
    

*   integrations object
    
    Contains a list of booleans indicating the integrations that are enabled (true) or disabled (false). By default, all integrations are enabled (returning an empty object). Set `"All": false` to reverse this behavior.
    
    *   *Enabled/Disabled integrations\** boolean
        
*   name string
    
    Required The name of the page.
    
*   properties object
    
    Additional properties for your event.
    
    *   category string
        
        The category of the page. This might be useful if you have a single page routes or have a flattened URL structure.
        
    *   *Page Properties\** any type
        
        Additional properties tha tyou want to send with the page event. By default, we capture \`url\`, \`title\`, and stuff.
        
*   timestamp string  (date-time)
    
    The ISO-8601 timestamp when the event originally took place. This is mostly useful when you backfill data past events. If you’re not backfilling data, you can leave this field empty and we’ll use the current time or server time.
    

## Group[](#group)

The Group method associates an identified person with a group—like a company, organization, project, online class or any other collective noun you come up with for the same concept. In Customer.io Journeys, we call groups [objectsAn object is a non-person entity that you can associate with one or more people—like a company, account, or online course.](/journeys/objects/).

Group calls are useful for integrations where you maintain relationships between people and larger organizations, like in Customer.io! In Customer.io Journeys, you can store groups as [objectsAn object is a non-person entity that you can associate with one or more people—like a company, account, or online course.](/journeys/objects/), and trigger campaigns based on a person’s relationship to an object—like an account, online class, and so on.

Find more details about `group`, including the **`group` payload**, in our [API spec](/integrations/api/cdp/#operation/group).

```go
client.Enqueue(analytics.Group{
  UserId:  "019mr8mf4r",
  GroupId: "56",
  Traits: map[string]interface{}{
    "name":        "Initech",
    "description": "Accounting Software",
  },
})
```

 Include `objectTypeId` when you send data to Customer.io

Customer.io supports different kinds of groups (called [objectsAn object is a non-person entity that you can associate with one or more people—like a company, account, or online course.](/journeys/objects/)) where each object has an [object type](/journeys/object-types/) represented by an incrementing integer beginning at 1. If you send `group` calls to Customer.io, you should include the object type ID or we’ll assume that the object type is 1.

*   groupId string
    
    Required ID of the group
    
*   integrations object
    
    Contains a list of booleans indicating the integrations that are enabled (true) or disabled (false). By default, all integrations are enabled (returning an empty object). Set `"All": false` to reverse this behavior.
    
    *   *Enabled/Disabled integrations\** boolean
        
*   timestamp string  (date-time)
    
    The ISO-8601 timestamp when the event originally took place. This is mostly useful when you backfill data past events. If you’re not backfilling data, you can leave this field empty and we’ll use the current time or server time.
    
*   traits object
    
    Additional information about the group.
    
    *   *Group Traits\** any type
        
        Additional traits you want to associate with this group.
        

*   groupId string
    
    Required ID of the group
    
*   integrations object
    
    Contains a list of booleans indicating the integrations that are enabled (true) or disabled (false). By default, all integrations are enabled (returning an empty object). Set `"All": false` to reverse this behavior.
    
    *   *Enabled/Disabled integrations\** boolean
        
*   timestamp string  (date-time)
    
    The ISO-8601 timestamp when the event originally took place. This is mostly useful when you backfill data past events. If you’re not backfilling data, you can leave this field empty and we’ll use the current time or server time.
    
*   traits object
    
    Additional information about the group.
    
    *   *Group Traits\** any type
        
        Additional traits you want to associate with this group.
        

## Alias[](#alias)

The Alias method combines two previously unassociated user identities. Some integrations automatically reconcile profiles with different identifiers based on whether you send `anonymousId`, `userId`, or another trait that the integration expects to be unique. But for integrations that don’t, you may need to send `alias` requests to do this.

In general, you won’t need to use the `alias` call; we try to handle user identification gracefully so you don’t need to merge profiles. But you may need to send `alias` calls to manage user identities in *some* data-out integrations.

For example, in [Mixpanel](/integrations/data-out/connections/mixpanel/#alias) it’s used to associate an anonymous user with an identified user once they sign up.

Here’s how you might use the `alias` call. In this case, we start with an `anonymous_user` and switch to an email address when a person provides their `userId`.

```go
// the anonymous user does actions ...
client.Enqueue(analytics.Track{
  Event:  "Anonymous Event",
  UserId: anonymousUser,
})

// the anonymous user signs up and is aliased
client.Enqueue(analytics.Alias{
  PreviousId: anonymousUser,
  UserId:     "019mr8mf4r",
})

// the identified user is identified
client.Enqueue(analytics.Identify{
  UserId: "019mr8mf4r",
  Traits: map[string]interface{}{
    "name":    "Michael Bolton",
    "email":   "mbolton@example.com",
    "plan":    "Enterprise",
    "friends": 42,
  },
})

// the identified user does actions ...
client.Enqueue(analytics.Track{
  Event:      "Item Viewed",
  UserId:     "019mr8mf4r",
  Properties: map[string]interface{}{
    "item": "lamp",
  },
})
```

*   previousId string
    
    Required The userId that you want to merge into the canonical profile.
    
*   userId string
    
    Required The userId that you want to keep. This is required if you haven’t already identified someone with one of our web or server-side libraries.
    

## Development settings[](#development)

While implementing Customer.io, you might want to make our library flush after every outgoing call. This can help you test your implementation and make sure that all of your calls work properly before you use this library in your production environment.

Set the `BatchSize` field in your configuration to 1 to make the library flush every after each request, so that you can make sure your calls are working properly.

```go
func main() {
  client, _ := analytics.NewWithConfig("YOUR_API_KEY", analytics.Config{
		BatchSize: 1,
	})
}
```

## Logging[](#logging)

The `Verbose` field of your configuration controls the level of logging, while the `Logger` field provides a hook to capture the log output:

```go
func main() {
  client, _ := analytics.NewWithConfig("YOUR_API_KEY", analytics.Config{
		Verbose: true,
		Logger:  analytics.StdLogger(log.New(os.Stderr, "customerio ", log.LstdFlags)),
	})
}
```

## Selecting Destinations[](#selecting-destinations)

You can pass an `integrations` object to `alias`, `group`, `identify`, `page` and `track` calls that lets you turn certain destinations on or off. By default all destinations are enabled. Passing `false` for an integration disables the call to that destination.

 You can also disable destinations in the user interface

If you disable a destination in the UI, you can’t enable a destination through the `integrations` object. Disabling an integration in the UI prevents us from sending data to a downstream integration all together.

You might want to do this for things like `alias` calls, which aren’t supported by all destinations.

In this case, Customer.io specifies the `track` to only go to Mixpanel. `All: false` disables all destinations except the ones you explicitly specify.

```go
client.Enqueue(analytics.Track{
  Event:  "Membership Upgraded",
  UserId: "019mr8mf4r",
  Integrations: map[string]interface{}{
    "All":      false,
    "Mixpanel": true,
  },
})
```

Destination flags are **case sensitive** and match [the integration’s name in our documentation](/integrations/catalog).

 You can filter track calls on the source’s *Schema* tab

We recommend that you filter events in our UI if you can. It’s easier than writing code, and you can update your source or make changes to your filters without involving developers!

## Backfilling historical data[](#backfilling-historical-data)

You can backfill data by adding a `timestamp` to your calls. This can be helpful if you’ve just switched to Customer.io.

You can only do this for destinations that accept timestamped data—most analytics tools like Mixpanel and Amplitude do. The notable destination that *doesn’t* support timestampped data is Google Analytics.

 Leave out the timestamp if you’re tracking real-time events

If you’re only tracking things as they happen, you can leave the `timestamp` out of your calls and we’ll timestamp requests for you.

## Context[](#context)

Context fields provide “context” for the events that you send—things like your app’s version. Our library sets [some defined context](/integrations/data-in/source-spec/common-fields/#the-context-object) fields by default, but you can override these fields or set custom context fields in a couple of different ways:

*   Globally, for all calls
*   At the event/call level

You can set custom context fields—fields outside the [ones we’ve defined](/integrations/data-in/source-spec/common-fields/#the-context-object). You must set custom context in the `Extra` field. We’ll automatically inline these properties in the serialized `context` structure.

 Global Context

#### Global Context[](#Global Context)

```go
client, _ := analytics.NewWithConfig("h97jamjwbh", analytics.Config{
  DefaultContext: &analytics.Context{
    App: analytics.AppInfo{
      Name:    "myapp",
      Version: "myappversion",
    },
  },
})
```

 Event-level context

#### Event-level context[](#Event-level context)

```go
client.Enqueue(analytics.Identify{
    UserId: "019mr8mf4r",
    Traits: analytics.NewTraits().
        Set("friends", 42),
    Context: &analytics.Context{
        Extra: map[string]interface{}{
            "active": true,
        },
    },
})
```

If you added both the global and event-level context changes above, then the identify call under *Event-level context* above would be serialized to:

```json
{
  "type": "identify",
  "userId": "019mr8mf4r",
  "traits": {
    "friends": 42,
  },
  "context": {
    "active": true,
    "library": {
      "name": "analytics-go",
      "version": "3.0.0"
    }
  }
}
```

## Batching[](#batching)

Our libraries are built to support high performance environments. It’s safe to use this library on a web server that serves hundreds of requests per second.

But every method you invoke **does not** result in an HTTP request. Instead, we queue requests in memory and then flush them in [batches](/integrations/api/cdp/#operation/batch), which allows for more efficient operation.

If batch messages do not arrive in your debugger and don’t throw errors, you may want to slow your script down. We run a message batching loop in a go-routine so if the script runs too quickly it won’t execute network calls before it exits the loop.

By default, our Go source library flushes:

*   every 20 messages (control with `FlushAt`)
*   if 5 seconds has passed since the last flush (control with `FlushAfter`)

There is a maximum of `500KB` per batch request and `32KB` per call. If you don’t want to batch messages, you can turn batching off by setting the `flushAt` option to `1`.

### Flushing and closing the client[](#flushing-and-closing-the-client)

When your application is shutting down or you need to ensure all queued events are sent, you should call the `Close()` method. This sends any queued events and then closes the client, preventing any further data from being sent.

```go
// Flush queued messages and close the client
client.Close()
```