Instrument and configure the Go SDK
이 페이지는 아직 귀하의 언어로 번역되지 않았습니다. 현재 작업 중이므로 곧 다시 확인해 주십시오.
This page covers everything after your first event: tracking, identity, plugins, delivery settings, logging, and shutdown. For signatures and every option, go to the Go SDK reference. For changes between versions, go to the Go SDK releases on GitHub.
The examples that start without 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()
Track events
Track a custom event
Pass an Event to Track(). Every event needs an EventType and either a UserID or a DeviceID. Add event properties in EventProperties.
client.Track(amplitude.Event{
EventType: "Button Clicked",
UserID: "user-12345",
EventProperties: map[string]interface{}{
"name": "Checkout",
"a property": "a value",
},
})
{
"event_type": "Button Clicked",
"user_id": "user-12345",
"event_properties": { "name": "Checkout", "a property": "a value" }
}
Track() queues the event and returns immediately. It doesn't block on the network.
Set event fields for one call
Event embeds EventOptions, which holds every other field Amplitude accepts: device and location fields, Price and Quantity, Time, InsertID, and more. For the full list, go to EventOptions.
import "time"
event := amplitude.Event{
EventType: "Song Played",
EventOptions: amplitude.EventOptions{
UserID: "user-12345",
DeviceID: "device-12345",
Platform: "Web",
Country: "United States",
UserAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
Price: 1.99,
},
}
event.SetTime(time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC))
client.Track(event)
{
"event_type": "Song Played",
"user_id": "user-12345",
"device_id": "device-12345",
"platform": "Web",
"country": "United States",
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
"price": 1.99,
"time": 1793534400000
}
Event.UserID and Event.DeviceID are shortcuts: the SDK copies them into EventOptions only when the EventOptions field is empty. SetTime() stores a time.Time as milliseconds since the Unix epoch. UserAgent requires 1.3.0 or later.
Set user properties
Build an Identify with one or more operations, then pass it to client.Identify() with the user's ID. The SDK sends an $identify event.
identify := amplitude.Identify{}
identify.Set("location", "LAX").
SetOnce("initial-location", "SFO").
Add("travel-count", 1).
Append("visited-locations", "SFO").
Prepend("recent-locations", "LAX").
PreInsert("unique-locations", "LAX").
PostInsert("unique-cities", "SFO").
Remove("saved-locations", "JFK").
Unset("old-location")
client.Identify(identify, amplitude.EventOptions{UserID: "user-12345"})
{
"event_type": "$identify",
"user_id": "user-12345",
"user_properties": {
"$set": { "location": "LAX" },
"$setOnce": { "initial-location": "SFO" },
"$add": { "travel-count": 1 },
"$append": { "visited-locations": "SFO" },
"$prepend": { "recent-locations": "LAX" },
"$preInsert": { "unique-locations": "LAX" },
"$postInsert": { "unique-cities": "SFO" },
"$remove": { "saved-locations": "JFK" },
"$unset": { "old-location": "-" }
}
}
Use each property in one operation only. If you reuse a property, the SDK logs Already used property ... ignoring operation but still sends both operations. ClearAll() removes every user property. The SDK logs Identify: Empty Properties and sends nothing for an Identify with no operations. For what each operation does, go to Identify.
User properties apply to later events
Amplitude updates the user's profile immediately, but charts show the new values only on events that arrive after the Identify. For details, go to User properties and events.
Assign a user to a group
Groups let you analyze users by the organization, team, or account they belong to. A group has a type, such as org-id, and a name, such as 15. A user can belong to several groups of the same type.
SetGroup() sends an $identify event that sets the group type as a user property, with the group names as its value. It replaces any names the user had for that type.
client.SetGroup("org-id", []string{"15", "21"}, amplitude.EventOptions{UserID: "user-12345"})
{
"event_type": "$identify",
"user_id": "user-12345",
"user_properties": { "$set": { "org-id": ["15", "21"] } }
}
To attribute one event to groups, set its Groups field:
event := amplitude.Event{
EventType: "Report Exported",
UserID: "user-12345",
Groups: map[string][]string{"org-id": {"15", "21"}},
}
event.Groups["sport"] = []string{"soccer"}
client.Track(event)
{
"event_type": "Report Exported",
"user_id": "user-12345",
"groups": { "org-id": ["15", "21"], "sport": ["soccer"] }
}
Set group properties
GroupIdentify() applies an Identify to one group. It sends a $groupidentify event. Like every event, it needs a UserID or DeviceID.
identify := amplitude.Identify{}
identify.Set("locale", "en-us")
client.GroupIdentify("org-id", "15", identify, amplitude.EventOptions{UserID: "user-12345"})
{
"event_type": "$groupidentify",
"user_id": "user-12345",
"groups": { "org-id": ["15"] },
"group_properties": { "$set": { "locale": "en-us" } }
}
Track revenue
Call Revenue() each time a user generates revenue. Set Price (with Quantity) or Revenue. The SDK sends a revenue_amount event that Amplitude's revenue charts read. Use negative values for refunds.
client.Revenue(amplitude.Revenue{
Price: 3.99,
Quantity: 3,
ProductID: "com.company.productID",
RevenueType: "purchase",
Currency: "USD",
}, amplitude.EventOptions{UserID: "user-12345"})
{
"event_type": "revenue_amount",
"user_id": "user-12345",
"event_properties": {
"$productId": "com.company.productID",
"$quantity": 3,
"$price": 3.99,
"$revenueType": "purchase",
"$currency": "USD",
"$receipt": "",
"$receiptSig": "",
"$revenue": 0
}
}
The SDK always sends all eight revenue properties, with empty values for fields you don't set. It doesn't send Revenue.Properties: to attach other properties to a purchase, track a separate event. Currency requires 1.1.0 or later. For every field, go to Revenue.
Attach tracking plan details
If you manage events with a tracking plan or send them through a named source, set Plan and IngestionMetadata in the Config. The SDK adds them to every event that doesn't set its own.
package main
import "github.com/amplitude/analytics-go/amplitude"
func main() {
config := amplitude.NewConfig("AMPLITUDE_API_KEY")
config.Plan = &litude.Plan{Branch: "main", Source: "backend", Version: "3"}
config.IngestionMetadata = &litude.IngestionMetadata{SourceName: "billing-service", SourceVersion: "2.1.0"}
client := amplitude.NewClient(config)
defer client.Shutdown()
client.Track(amplitude.Event{EventType: "Invoice Paid", UserID: "user-12345"})
}
{
"event_type": "Invoice Paid",
"user_id": "user-12345",
"plan": { "branch": "main", "source": "backend", "version": "3" },
"ingestion_metadata": { "source_name": "billing-service", "source_version": "2.1.0" }
}
Send events to more than one project
Each client sends to one project. Create one client per API key.
package main
import "github.com/amplitude/analytics-go/amplitude"
func main() {
clientA := amplitude.NewClient(amplitude.NewConfig("PROJECT_A_API_KEY"))
defer clientA.Shutdown()
clientB := amplitude.NewClient(amplitude.NewConfig("PROJECT_B_API_KEY"))
defer clientB.Shutdown()
clientA.Track(amplitude.Event{EventType: "Order Placed", UserID: "user-12345"})
clientB.Track(amplitude.Event{EventType: "Order Placed", UserID: "user-12345"})
}
Clients don't share queues, plugins, or settings.
Identity
How the SDK identifies users
The Go SDK keeps no identity state. It doesn't generate a device ID, store a user ID, or track sessions. Each event carries only the UserID, DeviceID, and SessionID you set on it. Amplitude rejects an event that has neither UserID nor DeviceID, and the SDK logs Invalid event, EventType and either UserID or DeviceID cannot be empty when you track one.
To group server events into a user's session, pass the SessionID your client app reports, in milliseconds since the Unix epoch.
Allow shorter IDs
Amplitude rejects user and device IDs shorter than five characters. To accept shorter IDs, set MinIDLength. The SDK sends it with each request as options.min_id_length.
package main
import "github.com/amplitude/analytics-go/amplitude"
func main() {
config := amplitude.NewConfig("AMPLITUDE_API_KEY")
config.MinIDLength = 3
client := amplitude.NewClient(config)
defer client.Shutdown()
client.Track(amplitude.Event{EventType: "Button Clicked", UserID: "u42"})
}
The SDK's default is 0, which leaves the option out of the request so Amplitude's minimum of five applies.
Opt out of tracking
Set OptOut to true to create a client that ignores every tracking call. Use it to turn tracking off for an environment, such as tests.
package main
import "github.com/amplitude/analytics-go/amplitude"
func main() {
config := amplitude.NewConfig("AMPLITUDE_API_KEY")
config.OptOut = true
client := amplitude.NewClient(config)
defer client.Shutdown()
client.Track(amplitude.Event{EventType: "Button Clicked", UserID: "user-12345"})
}
The client has no method to change opt-out after NewClient(). To stop tracking for one user, skip the call in your code.
Plugins
How plugins run
A plugin is a type with Name(), Type(), Setup(), and Execute() methods. Type() returns one of three plugin types, and the SDK runs them in this order for each event:
Beforeplugins (amplitude.PluginTypeBefore), in the order you add them. The built-incontextplugin runs first: it setstimeandinsert_idwhen they're empty, and setslibrary.Enrichmentplugins (amplitude.PluginTypeEnrichment), in the order you add them.Destinationplugins (amplitude.PluginTypeDestination). Each gets its own copy of the event, and they run concurrently. The built-inamplitudedestination uploads to Amplitude.
A Before or Enrichment plugin returns the event to pass on, or nil to drop it. Execute() can run on several goroutines at once when you call Track() from several goroutines, so guard shared state. If a plugin panics, the SDK recovers, logs Panic in plugin <name>.Execute, and passes the event on unchanged.
Enrich events
This Enrichment plugin gives each event an increasing EventID:
import "sync"
type addEventIDPlugin struct {
mu sync.Mutex
currentID int
}
func (p *addEventIDPlugin) Name() string { return "AddEventId" }
func (p *addEventIDPlugin) Type() amplitude.PluginType { return amplitude.PluginTypeEnrichment }
func (p *addEventIDPlugin) Setup(config amplitude.Config) {}
func (p *addEventIDPlugin) Execute(event *amplitude.Event) *amplitude.Event {
p.mu.Lock()
defer p.mu.Unlock()
p.currentID++
event.EventID = p.currentID
return event
}
client.Add(&addEventIDPlugin{})
client.Track(amplitude.Event{EventType: "Song Played", UserID: "user-12345"})
{ "event_type": "Song Played", "user_id": "user-12345", "event_id": 1 }
Add or remove a plugin
Add() calls the plugin's Setup() with the client's Config, then registers it. Remove() removes every plugin with the given name, including built-in ones.
client.Remove("AddEventId")
client.Track(amplitude.Event{EventType: "Button Clicked", UserID: "user-12345"})
Drop events
Return nil from Execute() to drop an event. This Before plugin drops events from test accounts:
import "strings"
type dropTestUsers struct{}
func (p *dropTestUsers) Name() string { return "drop-test-users" }
func (p *dropTestUsers) Type() amplitude.PluginType { return amplitude.PluginTypeBefore }
func (p *dropTestUsers) Setup(config amplitude.Config) {}
func (p *dropTestUsers) Execute(event *amplitude.Event) *amplitude.Event {
if strings.HasPrefix(event.UserID, "test-") {
return nil
}
return event
}
client.Add(&dropTestUsers{})
client.Track(amplitude.Event{EventType: "Song Played", UserID: "test-user-1"})
client.Track(amplitude.Event{EventType: "Song Played", UserID: "user-12345"})
Plugins receive the event after Track() has copied Event.UserID into EventOptions.UserID, so event.UserID holds the ID whichever field you set.
Send events to another destination
A Destination plugin receives a copy of every event. Its Execute() returns nothing. To have Flush() and Shutdown() reach your plugin, also implement Flush() and Shutdown() (the ExtendedDestinationPlugin interface).
import (
"bytes"
"encoding/json"
"net/http"
"time"
)
type myDestinationPlugin struct {
url string
config amplitude.Config
httpClient *http.Client
}
func (p *myDestinationPlugin) Name() string { return "MyDestinationPlugin" }
func (p *myDestinationPlugin) Type() amplitude.PluginType { return amplitude.PluginTypeDestination }
func (p *myDestinationPlugin) Setup(config amplitude.Config) {
p.config = config
p.httpClient = &http.Client{Timeout: 5 * time.Second}
}
func (p *myDestinationPlugin) Execute(event *amplitude.Event) {
body, err := json.Marshal(map[string]interface{}{"key": "secret", "events": event})
if err != nil {
p.config.Logger.Warnf("encoding event failed: %s", err)
return
}
resp, err := p.httpClient.Post(p.url, "application/json", bytes.NewReader(body))
if err != nil {
p.config.Logger.Warnf("sending event failed: %s", err)
return
}
resp.Body.Close()
}
client.Add(&myDestinationPlugin{url: "https://custom.domain.com"}) // your server's URL
client.Track(amplitude.Event{EventType: "Button Clicked", UserID: "user-12345"})
The plugin posts JSON like this:
{
"events": {
"event_type": "Button Clicked",
"user_id": "user-12345",
"time": 1794431065800,
"insert_id": "1c8aac41-8257-4bea-ab3f-de914e39df5e",
"library": "amplitude-go/1.3.1"
},
"key": "secret"
}
The built-in amplitude destination runs on its own goroutine, so a slow destination plugin doesn't delay uploads to Amplitude. It does delay the Track() call, which waits for every destination's Execute() to return.
Data delivery
How the SDK uploads events
The SDK queues events in memory and uploads them from a background goroutine:
- Timing: The SDK uploads every
FlushInterval(10 seconds by default), and as soon as the queue holdsFlushQueueSizeevents (200 by default). - Batch size: Each request holds up to
FlushQueueSize / FlushSizeDividerevents. The SDK sends a larger queue as several requests, one after another. - Capacity:
Track()hands events to the uploader through a buffer ofMaxStorageCapacityevents (20,000 by default). When the buffer is full, the SDK drops new events without logging. - Storage: The queue lives only in memory. The SDK loses unsent events when the process exits or crashes.
- Compression: The SDK sends plain JSON and doesn't compress request bodies.
| Response | What the SDK does |
|---|---|
2xx | Reports each event to ExecuteCallback with Event sent successfully. |
400 for some events | Drops the events Amplitude names as invalid, and retries the rest. |
400 for an invalid API key or missing field | Drops every event in the request. |
413 | Lowers the batch size for the rest of the client's life (by raising FlushSizeDivider) and retries. Drops a single event that's too large. |
429 | Drops events for users or devices over their daily quota. Waits RetryThrottledInterval (30 seconds) before it retries other throttled events. |
408, 5xx, or a timeout | Retries up to FlushMaxRetries (12) times after the first attempt. The wait doubles every two retries, starting at RetryBaseInterval (100 ms). |
| No response (DNS, connection refused) | Drops the events with HTTP request failed, without retrying. |
A retry waits for the next upload after its delay ends: the next FlushInterval tick, a full queue, or a Flush() call.
Tune upload performance
Raise FlushQueueSize to send fewer, larger requests. Lower FlushInterval to send events sooner. FlushInterval is a time.Duration, so always include a unit.
package main
import (
"time"
"github.com/amplitude/analytics-go/amplitude"
)
func main() {
config := amplitude.NewConfig("AMPLITUDE_API_KEY")
config.FlushQueueSize = 100 // events per request
config.FlushInterval = 5 * time.Second // upload every 5 seconds
config.FlushMaxRetries = 5 // retries after the first attempt
client := amplitude.NewClient(config)
defer client.Shutdown()
client.Track(amplitude.Event{EventType: "Button Clicked", UserID: "user-12345"})
}
The SDK treats 0 as unset for every numeric option and uses the default instead.
Choose a data region
If your Amplitude project is in the EU data center, set ServerZone to amplitude.ServerZoneEU. The SDK then sends to https://api.eu.amplitude.com/2/httpapi. Use the API key from your EU project.
package main
import "github.com/amplitude/analytics-go/amplitude"
func main() {
config := amplitude.NewConfig("AMPLITUDE_API_KEY")
config.ServerZone = amplitude.ServerZoneEU
client := amplitude.NewClient(config)
defer client.Shutdown()
client.Track(amplitude.Event{EventType: "Button Clicked", UserID: "user-12345"})
}
Send large batches to the Batch API
Set UseBatch to true to send to the Batch Event Upload API (https://api2.amplitude.com/batch, or https://api.eu.amplitude.com/batch with ServerZoneEU). The Batch API accepts larger payloads and has higher rate limits. The SDK uses the same FlushQueueSize and FlushInterval in both modes.
package main
import "github.com/amplitude/analytics-go/amplitude"
func main() {
config := amplitude.NewConfig("AMPLITUDE_API_KEY")
config.UseBatch = true
client := amplitude.NewClient(config)
defer client.Shutdown()
client.Track(amplitude.Event{EventType: "Button Clicked", UserID: "user-12345"})
}
Send events through a proxy
Set ServerURL to send every request to your own endpoint. ServerURL overrides ServerZone and UseBatch. Your proxy must forward the body unchanged to Amplitude and return Amplitude's status code and response body. The SDK uses them to decide what to retry.
package main
import "github.com/amplitude/analytics-go/amplitude"
func main() {
config := amplitude.NewConfig("AMPLITUDE_API_KEY")
config.ServerURL = "https://amplitude-proxy.example.com/2/httpapi"
client := amplitude.NewClient(config)
defer client.Shutdown()
client.Track(amplitude.Event{EventType: "Button Clicked", UserID: "user-12345"})
}
The SDK sends requests with Go's default HTTP transport, so it honors the HTTPS_PROXY and NO_PROXY environment variables. To use a forward proxy without changing the URL, set those variables instead of ServerURL.
Set a request timeout
ConnectionTimeout limits each upload request, from connecting to reading the response (10 seconds by default). The SDK retries a request that times out.
package main
import (
"time"
"github.com/amplitude/analytics-go/amplitude"
)
func main() {
config := amplitude.NewConfig("AMPLITUDE_API_KEY")
config.ConnectionTimeout = 3 * time.Second
client := amplitude.NewClient(config)
defer client.Shutdown()
client.Track(amplitude.Event{EventType: "Button Clicked", UserID: "user-12345"})
}
Get upload results
Set ExecuteCallback to receive the result for each event after the SDK finishes with it. For the sample and the codes it reports, go to Read the upload result. The SDK recovers a panic in the callback and logs Panic in callback.
Replace event storage
StorageFactory returns the queue that holds events waiting to upload. The default is storages.NewInMemoryEventStorage from github.com/amplitude/analytics-go/amplitude/storages. To use your own queue, return a type that implements EventStorage. The SDK calls it from its upload goroutine. Events that Track() drops because the buffer is full never reach storage.
Control logging
The default logger writes every level to standard error, including Debug messages that contain your API key and each event payload. In production, set a Logger that drops Debug messages. Any type with Debugf, Infof, Warnf, and Errorf methods works.
package main
import (
"log"
"github.com/amplitude/analytics-go/amplitude"
)
// quietLogger drops Debug and Info messages and keeps warnings and errors.
type quietLogger struct{}
func (quietLogger) Debugf(message string, args ...interface{}) {}
func (quietLogger) Infof(message string, args ...interface{}) {}
func (quietLogger) Warnf(message string, args ...interface{}) {
log.Printf("amplitude warn: "+message, args...)
}
func (quietLogger) Errorf(message string, args ...interface{}) {
log.Printf("amplitude error: "+message, args...)
}
func main() {
config := amplitude.NewConfig("AMPLITUDE_API_KEY")
config.Logger = quietLogger{}
client := amplitude.NewClient(config)
defer client.Shutdown()
client.Track(amplitude.Event{EventType: "Button Clicked", UserID: "user-12345"})
}
Error messages still include the payloads of failed events, but not the API key. To route messages to your own logging library, call it from these four methods.
Use the SDK in request handlers
Create one client at startup and share it. A client is safe to use from many goroutines. Don't create a client per request: each client starts its own upload goroutine, and only Shutdown() stops it.
import "net/http"
func signupHandler(client amplitude.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
client.Track(amplitude.Event{
EventType: "Sign Up Completed",
UserID: r.FormValue("user_id"),
})
w.WriteHeader(http.StatusCreated)
}
}
http.Handle("/signup", signupHandler(client))
Track() returns after it queues the event, so it doesn't add network time to the response. To try the handler without starting a server, call it with a recorded request:
import "net/http/httptest"
signupHandler(client)(httptest.NewRecorder(), httptest.NewRequest("POST", "/signup?user_id=user-12345", nil))
Flush before the process exits
Go doesn't run cleanup when main returns, and the SDK holds events only in memory. Before your program exits, call Shutdown(). It uploads queued events, waits for the upload, and then stops the client. In version 1.3.1 and later, it also waits for running ExecuteCallback calls before it stops. A client ignores every call after Shutdown().
Shutdown() makes one upload attempt. It doesn't wait for events that are waiting to retry, and the SDK loses them.
In a job worker or serverless function that reuses the client across invocations, call Flush() at the end of each invocation instead. Flush() uploads queued events and returns after the upload attempt. The client keeps running.
func handleJob(client amplitude.Client, jobID, userID string) {
client.Track(amplitude.Event{
EventType: "Job Completed",
UserID: userID,
EventProperties: map[string]interface{}{"jobId": jobID},
})
client.Flush()
}
handleJob(client, "job-77", "user-12345")
If the platform can stop the process without warning, handle SIGTERM and call Shutdown() from the handler.
이 내용이 도움이 되었나요?
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.