Go SDK reference
이 페이지는 아직 귀하의 언어로 번역되지 않았습니다. 현재 작업 중이므로 곧 다시 확인해 주십시오.
This reference documents every public export of the github.com/amplitude/analytics-go/amplitude package and its subpackages, and every Config option, verified against version 1.3.1. For options, go to Configuration options. To find the release that added or changed a feature, go to the Go SDK releases on GitHub.
package main
import "github.com/amplitude/analytics-go/amplitude"
func main() {
client := amplitude.NewClient(amplitude.NewConfig("AMPLITUDE_API_KEY"))
defer client.Shutdown()
}
The amplitude package holds the client, NewConfig, and aliases for the types most code needs. The types themselves live in subpackages:
| Package | Holds |
|---|---|
github.com/amplitude/analytics-go/amplitude | NewClient, NewConfig, Client, and aliases for Config, Event, Identify, Revenue, and the plugin types. |
github.com/amplitude/analytics-go/amplitude/types | The types behind the aliases, plus the IdentityOp constants and StorageEvent. |
github.com/amplitude/analytics-go/amplitude/constants | Default values, server URLs, and the SDK's library name and version. |
github.com/amplitude/analytics-go/amplitude/loggers | NewDefaultLogger. |
github.com/amplitude/analytics-go/amplitude/storages | NewInMemoryEventStorage. |
There are no top-level tracking functions. You call every method on a Client from NewClient(). The SDK reports upload results through ExecuteCallback, not through return values: no Client method returns an error.
The examples on this page that don't start with package main continue from this client:
import "github.com/amplitude/analytics-go/amplitude"
config := amplitude.NewConfig("AMPLITUDE_API_KEY")
client := amplitude.NewClient(config)
defer client.Shutdown()
Setup
NewConfig
Returns a Config with APIKey set and every other field at its zero value. NewClient() replaces zero values with defaults.
func NewConfig(apiKey string) Config
| Parameter | Type | Description |
|---|---|---|
apiKey | string | Your Amplitude project's API key. |
NewClient
Creates a client, applies defaults to unset options, adds the built-in plugins, and starts the upload goroutine. It doesn't validate the configuration or contact Amplitude.
func NewClient(config Config) Client
| Parameter | Type | Description |
|---|---|---|
config | Config | Go to Configuration options. The client keeps a copy; later changes have no effect. |
Config
Returns the client's configuration, with defaults applied.
Config() Config
import "fmt"
fmt.Println(client.Config().FlushQueueSize, client.Config().FlushInterval)
// 200 10s
Config.IsValid
Reports whether APIKey is set, FlushQueueSize and FlushInterval are greater than zero, and MinIDLength isn't negative. The SDK never calls it. A Config from NewConfig() reports false until defaults apply, so check client.Config().IsValid() instead.
func (c Config) IsValid() bool
Tracking
Track
Runs the event through plugins and queues it for upload. Returns after every destination plugin accepts the event. Does nothing after Shutdown() or when OptOut is true.
Track(event Event)
| Parameter | Type | Description |
|---|---|---|
event | Event | Needs EventType and either a user ID or a device ID. |
Before plugins run, Track() sets the event's Plan and IngestionMetadata from the Config when the event has none. It also copies Event.UserID and Event.DeviceID into empty EventOptions fields.
client.Track(amplitude.Event{EventType: "Song Played", UserID: "user-12345"})
Identify
Sends an $identify event that applies the Identify operations to the user's properties. If the Identify has no operations, logs Identify: Empty Properties and sends nothing.
Identify(identify Identify, eventOptions EventOptions)
| Parameter | Type | Description |
|---|---|---|
identify | Identify | The operations to apply. |
eventOptions | EventOptions | Needs UserID or DeviceID. |
identify := amplitude.Identify{}
identify.Set("plan", "pro")
client.Identify(identify, amplitude.EventOptions{UserID: "user-12345"})
GroupIdentify
Sends a $groupidentify event that applies the Identify operations to one group's properties.
GroupIdentify(groupType string, groupName string, identify Identify, eventOptions EventOptions)
| Parameter | Type | Description |
|---|---|---|
groupType | string | The group type, such as org-id. |
groupName | string | The group name, such as 15. |
identify | Identify | The operations to apply to the group. |
eventOptions | EventOptions | Needs UserID or DeviceID. |
identify := amplitude.Identify{}
identify.Set("industry", "media")
client.GroupIdentify("org-id", "15", identify, amplitude.EventOptions{UserID: "user-12345"})
SetGroup
Sends an $identify event that sets groupType as a user property, with groupName as its value. Doesn't set the event's groups field.
SetGroup(groupType string, groupName []string, eventOptions EventOptions)
| Parameter | Type | Description |
|---|---|---|
groupType | string | The group type, such as org-id. |
groupName | []string | One or more group names. |
eventOptions | EventOptions | Needs UserID or DeviceID. |
client.SetGroup("org-id", []string{"15"}, amplitude.EventOptions{UserID: "user-12345"})
Revenue
Sends a revenue_amount event with the revenue fields as event properties. If both Price and Revenue are 0, logs Invalid Revenue: Either Revenue or Price should be set and sends nothing.
Revenue(revenue Revenue, eventOptions EventOptions)
| Parameter | Type | Description |
|---|---|---|
revenue | Revenue | The purchase. |
eventOptions | EventOptions | Needs UserID or DeviceID. |
client.Revenue(amplitude.Revenue{Price: 9.99, Quantity: 1, ProductID: "pro-monthly"}, amplitude.EventOptions{UserID: "user-12345"})
Delivery
Flush
Uploads every queued event that isn't waiting to retry, and returns after the upload attempt. The client keeps running. Calls Flush() on every destination plugin that implements it.
Flush()
client.Track(amplitude.Event{EventType: "Song Played", UserID: "user-12345"})
client.Flush()
Shutdown
Stops accepting events, uploads queued events once, stops the upload goroutine, and calls Shutdown() on every destination plugin that implements it. In version 1.3.1 and later, it also waits for running ExecuteCallback calls to return. The SDK discards events that are waiting to retry. A second call does nothing.
Shutdown()
package main
import "github.com/amplitude/analytics-go/amplitude"
func main() {
client := amplitude.NewClient(amplitude.NewConfig("AMPLITUDE_API_KEY"))
client.Track(amplitude.Event{EventType: "Song Played", UserID: "user-12345"})
client.Shutdown()
client.Track(amplitude.Event{EventType: "Ignored", UserID: "user-12345"}) // ignored after Shutdown
}
Plugins
Add
Calls the plugin's Setup() with the client's Config, then registers it by its Type(). Logs an error and ignores a plugin whose Type() isn't one of the three plugin types.
Add(plugin Plugin)
| Parameter | Type | Description |
|---|---|---|
plugin | Plugin | A BeforePlugin, EnrichmentPlugin, DestinationPlugin, or ExtendedDestinationPlugin. |
Remove
Removes every plugin, of any type, whose Name() matches. Removing amplitude stops uploads to Amplitude; removing context stops the SDK from setting time, insert_id, and library.
Remove(pluginName string)
| Parameter | Type | Description |
|---|---|---|
pluginName | string | The Name() of the plugin to remove. |
For plugin examples, go to Plugins.
Event
The event to track. Fields other than these come from the embedded EventOptions.
| Field | Type | JSON | Description |
|---|---|---|---|
EventType | string | event_type | Required. The event name. |
EventOptions | EventOptions | (embedded) | Identity, device, location, revenue, and timing fields. |
EventProperties | map[string]interface{} | event_properties | Event properties. |
UserProperties | map[IdentityOp]map[string]interface{} | user_properties | User property operations. Identify() fills it for you. |
Groups | map[string][]string | groups | Group names by group type. |
GroupProperties | map[IdentityOp]map[string]interface{} | group_properties | Group property operations. GroupIdentify() fills it for you. |
UserID | string | Not sent directly | Shortcut. Track() copies it to EventOptions.UserID when that field is empty. |
DeviceID | string | Not sent directly | Shortcut. Track() copies it to EventOptions.DeviceID when that field is empty. |
Event has one method:
func (e Event) Clone() Event
Clone() returns a deep copy of the maps and slices. The SDK gives each destination plugin a clone.
Event type constants
| Constant | Value |
|---|---|
amplitude.IdentifyEventType | $identify |
amplitude.GroupIdentifyEventType | $groupidentify |
amplitude.RevenueEventType | revenue_amount |
EventOptions
Optional fields Amplitude accepts on any event. The SDK leaves each field out of the request when it holds its zero value.
| Field | Type | JSON | Description |
|---|---|---|---|
UserID | string | user_id | The user's ID. Each event needs this or DeviceID. |
DeviceID | string | device_id | The device's ID. |
UserAgent | string | user_agent | The user agent of the client that generated the event. Requires 1.3.0 or later. |
Time | int64 | time | Milliseconds since the Unix epoch. The context plugin sets the current time when it's 0. |
InsertID | string | insert_id | Deduplication ID. The context plugin sets a random UUID when it's empty. |
Library | string | library | The context plugin always overwrites it with amplitude-go/<version>. |
LocationLat | float64 | location_lat | Latitude. |
LocationLng | float64 | location_lng | Longitude. |
AppVersion | string | app_version | The app version. |
VersionName | string | version_name | The version name. |
Platform | string | platform | The platform. |
OSName | string | os_name | The operating system name. |
OSVersion | string | os_version | The operating system version. |
DeviceBrand | string | device_brand | The device brand. |
DeviceManufacturer | string | device_manufacturer | The device manufacturer. |
DeviceModel | string | device_model | The device model. |
Carrier | string | carrier | The mobile carrier. |
Country | string | country | The country. |
Region | string | region | The region or state. |
City | string | city | The city. |
DMA | string | dma | The designated market area. |
IDFA | string | idfa | iOS identifier for advertisers. |
IDFV | string | idfv | iOS identifier for vendors. |
ADID | string | adid | Google advertising ID. |
AndroidID | string | android_id | Android ID. |
Language | string | language | The language. |
IP | string | ip | The IP address. Amplitude uses it for location when location fields are empty. |
Price | float64 | price | The price of the item purchased. |
Quantity | int | quantity | The quantity purchased. |
Revenue | float64 | revenue | The revenue amount. |
Currency | string | currency | The currency code, such as USD. Requires 1.1.0 or later. |
ProductID | string | productId | The product ID. |
RevenueType | string | revenueType | The revenue type. |
EventID | int | event_id | An event counter. The SDK doesn't set it. |
SessionID | int | session_id | Session start time in milliseconds since the Unix epoch. The SDK doesn't set it. |
PartnerID | string | partner_id | A partner ID. |
Plan | *Plan | plan | Tracking plan details. Defaults to Config.Plan. |
IngestionMetadata | *IngestionMetadata | ingestion_metadata | Source details. Defaults to Config.IngestionMetadata. |
EventOptions has two methods:
func (eo *EventOptions) SetTime(time time.Time)
func (eo *EventOptions) Clone() *EventOptions
SetTime() sets Time from a time.Time, in milliseconds. Clone() returns a copy with its own Plan and IngestionMetadata.
Identify struct
Builds user or group property operations. The zero value is ready to use. Each method records one operation and returns the *Identify, so you can chain calls.
| Method | Operation | Description |
|---|---|---|
Set(property string, value interface{}) | $set | Sets the property's value. |
SetOnce(property string, value interface{}) | $setOnce | Sets the value only if the property has none yet. |
Add(property string, value interface{}) | $add | Adds a number to the property. Amplitude treats a missing property as 0. |
Append(property string, value interface{}) | $append | Appends a value or values to an array property. Amplitude treats a missing property as an empty array. |
Prepend(property string, value interface{}) | $prepend | Prepends a value or values to an array property. |
PreInsert(property string, value interface{}) | $preInsert | Adds values to the start of an array property, skipping values already in it. |
PostInsert(property string, value interface{}) | $postInsert | Adds values to the end of an array property, skipping values already in it. |
Remove(property string, value interface{}) | $remove | Removes a value or values from an array property. |
Unset(property string) | $unset | Removes the property. Sends "-" as the value. |
ClearAll() | $clearAll | Removes every user property. |
The SDK logs a warning, but still records the operation, when a property is empty, a value is nil, the Identify already holds $clearAll, or the property already appears in another operation.
| Field | Type | Description |
|---|---|---|
Properties | map[IdentityOp]map[string]interface{} | The recorded operations, sent as user_properties or group_properties. |
PropertiesSet | map[string]struct{} | The properties used so far. |
func (i *Identify) Validate() ([]string, []string)
Validate() returns errors (Empty Properties when the Identify holds no operations) and the warnings collected so far. Identify() and GroupIdentify() call it for you.
IdentityOp constants
The constants live in the types package. The amplitude package aliases the IdentityOp type only.
| Constant | Value |
|---|---|
types.IdentityOpSet | $set |
types.IdentityOpSetOnce | $setOnce |
types.IdentityOpAdd | $add |
types.IdentityOpAppend | $append |
types.IdentityOpPrepend | $prepend |
types.IdentityOpPreInsert | $preInsert |
types.IdentityOpPostInsert | $postInsert |
types.IdentityOpRemove | $remove |
types.IdentityOpUnset | $unset |
types.IdentityOpClearAll | $clearAll |
types.UnsetValue (string) | - |
Revenue struct
A purchase to send with Client.Revenue().
| Field | Type | Default | Sent as | Description |
|---|---|---|---|---|
Price | float64 | 0 | $price | The price of one item. Set this or Revenue. Negative values indicate refunds. |
Quantity | int | 0 | $quantity | The number of items. |
ProductID | string | "" | $productId | An identifier for the product. |
RevenueType | string | "" | $revenueType | The revenue type, such as purchase, tax, or refund. |
Currency | string | "" | $currency | The currency code, such as USD. Requires 1.1.0 or later. |
Receipt | string | "" | $receipt | The receipt identifier. |
ReceiptSig | string | "" | $receiptSig | The receipt signature. |
Revenue | float64 | 0 | $revenue | The total revenue. Set this or Price. Negative values indicate refunds. |
Properties | map[string]interface{} | nil | Not sent | Client.Revenue() ignores this field. |
func (r Revenue) Validate() []string
Validate() returns Either Revenue or Price should be set when both are 0.
Plugin
Every plugin implements Plugin and one of the typed interfaces below.
type Plugin interface {
Name() string
Type() PluginType
Setup(config Config)
}
type BeforePlugin interface {
Plugin
Execute(event *Event) *Event
}
type EnrichmentPlugin interface {
Plugin
Execute(event *Event) *Event
}
type DestinationPlugin interface {
Plugin
Execute(event *Event)
}
type ExtendedDestinationPlugin interface {
DestinationPlugin
Flush()
Shutdown()
}
| Method | Description |
|---|---|
Name() | The name Remove() matches. |
Type() | One of the PluginType constants. |
Setup() | Add() calls it once with the client's Config. Returns nothing. If it panics, the SDK logs the panic and never calls Execute(). |
Execute() | Before and Enrichment: return the event to pass on, or nil to drop it. Destination: returns nothing and receives its own copy of the event. |
Flush(), Shutdown() | Extended destinations only. Client.Flush() and Client.Shutdown() call them. |
The SDK recovers panics in every plugin method and logs Panic in plugin <name>.<method>.
PluginType
| Constant | Runs |
|---|---|
amplitude.PluginTypeBefore | First, in the order added, after the built-in context plugin. |
amplitude.PluginTypeEnrichment | Second, in the order added. |
amplitude.PluginTypeDestination | Last, all at once, each on its own copy of the event. |
ExecuteResult
The value the SDK passes to Config.ExecuteCallback for each event it finishes with.
| Field | Type | Description |
|---|---|---|
PluginName | string | The destination that sent the event: amplitude for the built-in destination. |
Event | *Event | The event as sent. |
Code | int | The code from Amplitude's response, the HTTP status for a response that isn't JSON, or 0 when no response arrived. |
Message | string | Event sent successfully. on success, otherwise the reason. Go to Read the upload result. |
Types
Plan
Tracking plan details, sent as plan.
| Field | Type | JSON |
|---|---|---|
Branch | string | branch |
Source | string | source |
Version | string | version |
VersionID | string | versionId |
IngestionMetadata
Source details, sent as ingestion_metadata.
| Field | Type | JSON |
|---|---|---|
SourceName | string | source_name |
SourceVersion | string | source_version |
ServerZone
A string type. Use amplitude.ServerZoneUS ("US") or amplitude.ServerZoneEU ("EU").
Logger
Any type with these methods. The SDK formats messages with fmt-style verbs.
type Logger interface {
Debugf(message string, args ...interface{})
Infof(message string, args ...interface{})
Warnf(message string, args ...interface{})
Errorf(message string, args ...interface{})
}
loggers.NewDefaultLogger() returns the default: a standard library log.Logger that writes every level to standard error with the prefix amplitude-analytics - .
EventStorage
The queue behind Config.StorageFactory.
type EventStorage interface {
PushNew(event *StorageEvent)
ReturnBack(events ...*StorageEvent)
Pull(count int, before time.Time) []*StorageEvent
Count(before time.Time) int
}
| Method | Contract |
|---|---|
PushNew | Adds a new event to the end of the queue. |
ReturnBack | Puts events back after a failed upload. Events with a zero RetryAt go to the front of the queue. |
Pull | Removes and returns up to count events: new events first, then retries whose RetryAt is before before. |
Count | The number of events Pull could return now. |
types.StorageEvent embeds *Event and adds RetryAt time.Time and RetryCount int. storages.NewInMemoryEventStorage() returns the default, in-memory implementation.
Constants
The constants package exports values the SDK uses. Changing them has no effect on a running client.
| Name | Value |
|---|---|
SdkLibrary, SdkVersion | amplitude-go and the SDK version. Sent together as library. |
ServerURLs | US: https://api2.amplitude.com/2/httpapi. EU: https://api.eu.amplitude.com/2/httpapi. |
ServerBatchURLs | US: https://api2.amplitude.com/batch. EU: https://api.eu.amplitude.com/batch. |
DefaultConfig | The defaults in Configuration options. |
RevenueProductID through DefaultRevenue | The revenue property names, such as $productId. |
MaxPropertyKeys, MaxStringLength | 1024. The SDK doesn't enforce them. |
Configuration options
Set options on the Config from NewConfig() before you call NewClient(). For every numeric and duration option, 0 means "use the default".
Connection
| Option | Type | Default | Description |
|---|---|---|---|
APIKey | string | "" (set by NewConfig()) | Required. The API key of the project to send events to. |
ServerZone | ServerZone | amplitude.ServerZoneUS | The data center: ServerZoneUS or ServerZoneEU. |
UseBatch | bool | false | Send to the Batch Event Upload API (/batch) instead of the HTTP V2 API (/2/httpapi). |
ServerURL | string | https://api2.amplitude.com/2/httpapi, from ServerZone and UseBatch | The upload endpoint. When set, overrides ServerZone and UseBatch. |
ConnectionTimeout | time.Duration | 10 * time.Second | The time limit for each upload request. |
MinIDLength | int | 0 (not sent; Amplitude's minimum of 5 applies) | The minimum length of user_id and device_id, sent as options.min_id_length. |
Batching and retries
| Option | Type | Default | Description |
|---|---|---|---|
FlushInterval | time.Duration | 10 * time.Second | How often the SDK uploads queued events. Include a unit: 5000 is 5000 nanoseconds. |
FlushQueueSize | int | 200 | The queue length that starts an upload, and the largest batch per request (before FlushSizeDivider). |
FlushSizeDivider | int | 1 | Divides FlushQueueSize to get the batch size. The SDK raises it by one after each 413 response. |
FlushMaxRetries | int | 12 | Retries after the first attempt, for timeouts, 408, and 5xx responses. |
RetryBaseInterval | time.Duration | 100 * time.Millisecond | The first retry delay. The delay doubles every two retries. |
RetryThrottledInterval | time.Duration | 30 * time.Second | The delay before the SDK retries events Amplitude throttled with 429. |
MaxStorageCapacity | int | 20000 | The size of the buffer between Track() and the uploader. When it's full, the SDK drops new events. |
StorageFactory | func() EventStorage | storages.NewInMemoryEventStorage | Creates the queue for events waiting to upload. Go to EventStorage. |
Behavior
| Option | Type | Default | Description |
|---|---|---|---|
OptOut | bool | false | When true, the client ignores every tracking call. You can't change it after NewClient(). |
ExecuteCallback | func(result ExecuteResult) | nil | The SDK calls it once for each event it finishes with. Go to ExecuteResult. |
Logger | Logger | loggers.NewDefaultLogger() | Receives the SDK's messages. The default writes every level, including the API key at Debug, to standard error. |
Plan | *Plan | nil | Added to events that don't set their own Plan. |
IngestionMetadata | *IngestionMetadata | nil | Added to events that don't set their own IngestionMetadata. |
이 내용이 도움이 되었나요?
For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.