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.

go
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:

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:

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

go
func NewConfig(apiKey string) Config

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.

go
func NewClient(config Config) Client

Config

Returns the client's configuration, with defaults applied.

go
Config() Config
go
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.

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

go
Track(event Event)

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.

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

go
Identify(identify Identify, eventOptions EventOptions)
go
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.

go
GroupIdentify(groupType string, groupName string, identify Identify, eventOptions EventOptions)
go
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.

go
SetGroup(groupType string, groupName []string, eventOptions EventOptions)
go
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.

go
Revenue(revenue Revenue, eventOptions EventOptions)
go
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.

go
Flush()
go
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.

go
Shutdown()
go
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.

go
Add(plugin Plugin)

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.

go
Remove(pluginName string)

For plugin examples, go to Plugins.

Event

The event to track. Fields other than these come from the embedded EventOptions.

Event has one method:

go
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

EventOptions

Optional fields Amplitude accepts on any event. The SDK leaves each field out of the request when it holds its zero value.

EventOptions has two methods:

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

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.

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

Revenue struct

A purchase to send with Client.Revenue().

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

go
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()
}

The SDK recovers panics in every plugin method and logs Panic in plugin <name>.<method>.

PluginType

ExecuteResult

The value the SDK passes to Config.ExecuteCallback for each event it finishes with.

Types

Plan

Tracking plan details, sent as plan.

IngestionMetadata

Source details, sent as ingestion_metadata.

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.

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

go
type EventStorage interface {
	PushNew(event *StorageEvent)
	ReturnBack(events ...*StorageEvent)
	Pull(count int, before time.Time) []*StorageEvent
	Count(before time.Time) int
}

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.

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

Batching and retries

Behavior

이 내용이 도움이 되었나요?

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.

이 페이지에서