Go 基础 API
以下示例使用已初始化的 analytics。安装见Go 集成,发送方式见上报方式,事件定义见服务端事件与用户操作。
事件与画像操作
生命周期事件 (TrackLifecycle / TrackLifecycleContext)
用于微服务中间件、定时任务或分布式事务的耗时与状态追踪:
go
func processTransaction(ctx context.Context, identity server.Identity, txID string) error {
start := time.Now()
// 1. 记录事务开始
analytics.TrackLifecycleContext(ctx, server.LifecycleInput{
Options: server.OperationOptions{Identity: identity},
Kind: server.LifecycleTransaction,
Name: "billing-transaction",
Phase: server.LifecycleStarted,
OperationID: txID,
})
err := executeDBCall()
durationMs := time.Since(start).Milliseconds()
if err != nil {
// 2. 事务失败记录
analytics.TrackLifecycleContext(ctx, server.LifecycleInput{
Options: server.OperationOptions{Identity: identity},
Kind: server.LifecycleTransaction,
Name: "billing-transaction",
Phase: server.LifecycleFailed,
OperationID: txID,
DurationMs: &durationMs,
ErrorType: "DATABASE_TIMEOUT",
})
return err
}
// 3. 事务成功记录
analytics.TrackLifecycleContext(ctx, server.LifecycleInput{
Options: server.OperationOptions{Identity: identity},
Kind: server.LifecycleTransaction,
Name: "billing-transaction",
Phase: server.LifecycleCompleted,
OperationID: txID,
DurationMs: &durationMs,
})
return nil
}用户画像操作 (ProfileSet / ProfileDelete)
画像方法提交的是操作事件;实际画像更新、并发原子性和删除范围取决于接收端实现。详见服务端操作语义。
go
identity := server.Identity{UserID: "user_1024"}
// 设置或覆盖画像属性
analytics.ProfileSet(identity, map[string]any{
"vip_level": 4,
})
// 提交数值画像字段累加请求
analytics.ProfileIncrement(identity, map[string]any{"total_logins": 1})
// 提交用户画像删除请求
analytics.ProfileDelete(identity)请求上下文属性
配置 ContextProperties 从请求的 context.Context 提取 trace_id 等字段,调用 TrackContext(ctx, ...) 时附加到事件:
go
type contextKey string
const TraceIDKey contextKey = "trace_id"
// 1. 在宿主启动函数中注入提取规则
func initAnalyticsWithTrace() error {
client, err := server.NewClient(server.Options{
Endpoint: "https://collector.example.com/v1/events/batch",
ProjectKey: "your-project-key", // 实际应用从宿主配置读取。
ContextProperties: func(ctx context.Context) map[string]any {
props := make(map[string]any)
if traceID, ok := ctx.Value(TraceIDKey).(string); ok && traceID != "" {
props["trace_id"] = traceID
}
return props
},
})
if err != nil { return err }
analytics = client
return nil
}
// 2. 业务中传入 context 即可自动附带 trace_id
func HandleRequest(ctx context.Context) {
analytics.TrackContext(ctx, server.TrackInput{
EventName: "button_clicked",
Identity: server.Identity{UserID: "u123"},
Properties: map[string]any{"target": "checkout"},
})
}