Documentation
¶
Overview ¶
Package analytics 提供 AES 加密支持
本文件包含: 1. AESClient - 独立的加密客户端(向后兼容) 2. AES 加密/解密函数 - 可被 Client 复用 3. PKCS7 填充/去填充辅助函数
注意:推荐使用 Client + WithEncryption 选项,而非直接使用 AESClient
Package analytics 提供轻量级、易用的分析统计客户端 SDK ¶
快速开始:
client := analytics.NewClient("http://your-server.com", "YourApp")
defer client.Close()
// 可选:上报安装信息
client.ReportInstall()
client.Track("event_name", map[string]interface{}{
"key": "value",
})
Example (ClientInfo) ¶
演示如何获取客户端信息
package main
import (
"fmt"
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
client := analytics.NewClient("http://localhost:8080", "MyApp")
defer client.Close()
fmt.Printf("Device ID: %s\n", client.GetDeviceID())
fmt.Printf("Session ID: %s\n", client.GetSessionID())
// Output (示例输出,实际值会不同):
// Device ID: abc-123-def-456
// Session ID: xyz-789-uvw-012
}
Example (EncryptionComparison) ¶
Example_encryptionComparison 对比加密和非加密客户端
package main
import (
"fmt"
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
serverURL := "http://localhost:8080"
productName := "MyApp"
// 场景1: 普通客户端(无加密)
normalClient := analytics.NewClient(serverURL, productName)
defer normalClient.Close()
normalClient.Track("page_view", map[string]interface{}{
"page": "/home",
})
// 场景2: 加密客户端
encryptedClient := analytics.NewClient(
serverURL,
productName,
analytics.WithEncryption("your-32-byte-secret-key-here!"),
)
defer encryptedClient.Close()
// 敏感数据使用加密
encryptedClient.Track("user_login", map[string]interface{}{
"email": "user@example.com",
"ip": "192.168.1.1",
"password": "***", // 敏感数据
})
fmt.Println("Comparison complete")
}
Output: Comparison complete
Example (ErrorHandling) ¶
Example_errorHandling 演示错误处理
package main
import (
"log"
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
client := analytics.NewClient(
"http://localhost:8080",
"MyApp",
analytics.WithDebug(true),
analytics.WithLogger(log.Default()),
)
defer client.Close()
// 异步发送(不阻塞,如果缓冲区满会丢弃)
client.Track("normal_event", map[string]interface{}{
"data": "value",
})
// 对于关键事件,发送后立即刷新并检查连接
client.Track("critical_event", map[string]interface{}{
"important": "data",
})
client.Flush() // 确保事件已发送
log.Println("Critical event sent")
}
Example (FullOptions) ¶
Example_fullOptions 演示完整配置选项
package main
import (
"log"
"time"
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
client := analytics.NewClient(
"http://localhost:8080",
"MyApp",
analytics.WithDeviceID("device-123"),
analytics.WithUserID("user-456"),
analytics.WithTimeout(15*time.Second),
analytics.WithBatchSize(50),
analytics.WithFlushInterval(10*time.Second),
analytics.WithDebug(true),
analytics.WithLogger(log.Default()),
)
defer client.Close()
// 跟踪事件
client.Track("button_click", map[string]interface{}{
"button": "login",
"screen": "home",
})
// 跟踪用户事件(推荐方式,灵活的属性)
client.Track("user_login", map[string]interface{}{
"category": "user",
"action": "login",
"method": "email",
})
// 批量跟踪
events := []analytics.Event{
{Name: "event1", Properties: map[string]interface{}{"key": "value1"}},
{Name: "event2", Properties: map[string]interface{}{"key": "value2"}},
}
client.TrackBatch(events)
// 发送重要事件并等待完成(推荐方式)
client.Track("important_event", map[string]interface{}{
"data": "must be sent immediately",
})
client.Flush() // 等待发送完成
log.Println("All events sent successfully")
}
Example (Gaming) ¶
Example_gaming 演示在游戏中使用
package main
import (
"time"
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
client := analytics.NewClient(
"http://game-analytics.example.com",
"MyGame",
analytics.WithDeviceID("switch-12345"),
analytics.WithBatchSize(200), // 游戏可能产生大量事件
analytics.WithFlushInterval(30*time.Second), // 降低网络频率
)
defer client.Close()
// 跟踪游戏事件
client.Track("level_complete", map[string]interface{}{
"level": 5,
"score": 1500,
"duration": 120, // 秒
})
client.Track("item_purchase", map[string]interface{}{
"item": "sword",
"currency": "gold",
"amount": 100,
})
client.Track("achievement_unlock", map[string]interface{}{
"achievement": "first_blood",
"timestamp": time.Now().Unix(),
})
}
Example (MobileApp) ¶
Example_mobileApp 演示在移动应用中使用
package main
import (
"time"
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
// 从持久化存储读取或生成设备ID
deviceID := loadDeviceID() // 假设有这个函数
client := analytics.NewClient(
"http://mobile-analytics.example.com",
"MobileApp",
analytics.WithDeviceID(deviceID),
analytics.WithBufferSize(500), // 移动设备可能间歇性联网
analytics.WithTimeout(30*time.Second), // 移动网络可能较慢
)
defer client.Close()
// 跟踪屏幕浏览
client.Track("screen_view", map[string]interface{}{
"screen_name": "home",
"previous": "splash",
})
// 跟踪用户行为
client.Track("button_tap", map[string]interface{}{
"button_id": "share",
"content": "article_123",
})
// 在应用进入后台时刷新
client.Flush()
}
// loadDeviceID 假设的辅助函数
func loadDeviceID() string {
return "device-12345"
}
Example (QuickStart) ¶
Example_quickStart 演示最简单的 3 行使用方式
package main
import (
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
client := analytics.NewClient("http://localhost:8080", "MyApp")
defer client.Close()
client.Track("page_view", map[string]interface{}{
"page": "/home",
"referrer": "google.com",
})
}
Example (UserTracking) ¶
Example_userTracking 演示用户跟踪
package main
import (
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
client := analytics.NewClient("http://localhost:8080", "MyApp")
defer client.Close()
// 用户登录后设置用户ID
onUserLogin := func(userID string) {
client.SetUserID(userID)
client.Track("user_login", map[string]interface{}{
"method": "email",
})
}
// 用户登出后清除用户ID
onUserLogout := func() {
client.Track("user_logout", nil)
client.SetUserID("")
}
onUserLogin("user-123")
// 跟踪用户行为
client.Track("profile_view", map[string]interface{}{
"user_id": client.GetDeviceID(),
})
onUserLogout()
}
Example (WebApplication) ¶
Example_webApplication 演示在 Web 应用中使用
package main
import (
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
// 在应用启动时创建客户端
analyticsClient := analytics.NewClient(
"http://analytics.example.com",
"WebApp",
analytics.WithUserID("user-123"),
analytics.WithBatchSize(100),
)
// 在关闭时清理
defer analyticsClient.Close()
// 在处理请求时跟踪事件
handleRequest := func() {
analyticsClient.Track("api_request", map[string]interface{}{
"endpoint": "/api/users",
"method": "GET",
"status": 200,
})
}
handleRequest()
}
Index ¶
- Variables
- func AESDecrypt(key []byte, ciphertextBase64 string) ([]byte, error)
- func AESEncrypt(key []byte, plaintext []byte) (string, error)
- type AESClientdeprecated
- type Client
- func (c *Client) Close() error
- func (c *Client) Flush()
- func (c *Client) GetDeviceID() string
- func (c *Client) GetSessionID() string
- func (c *Client) ReportInstall()
- func (c *Client) ReportInstallWithCallback(callback func(error))
- func (c *Client) SetUserID(userID string)
- func (c *Client) Track(eventName string, properties map[string]interface{})
- func (c *Client) TrackAppExit(properties map[string]interface{})
- func (c *Client) TrackAppLaunch(properties map[string]interface{})
- func (c *Client) TrackBatch(events []Event)
- func (c *Client) TrackEvent(category, action, label string, value float64)deprecated
- func (c *Client) TrackSync(eventName string, properties map[string]interface{}) errordeprecated
- type ClientError
- type ClientOption
- func WithBatchSize(size int) ClientOption
- func WithBufferSize(size int) ClientOption
- func WithDebug(debug bool) ClientOption
- func WithDeviceID(deviceID string) ClientOption
- func WithEncryption(secretKey string) ClientOption
- func WithFlushInterval(interval time.Duration) ClientOption
- func WithLogger(logger Logger) ClientOption
- func WithTimeout(timeout time.Duration) ClientOption
- func WithUserID(userID string) ClientOption
- type EncryptionConfig
- type Event
- type InstallInfo
- type Logger
- type NetworkError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidConfig 配置无效 ErrInvalidConfig = errors.New("invalid configuration") // ErrInvalidServerURL 服务器地址无效 ErrInvalidServerURL = errors.New("invalid server URL") // ErrInvalidProductName 产品名称无效 ErrInvalidProductName = errors.New("invalid product name") // ErrNetworkTimeout 网络超时 ErrNetworkTimeout = errors.New("network timeout") // ErrNetworkFailure 网络请求失败 ErrNetworkFailure = errors.New("network request failed") // ErrEncryptionFailed 加密失败 ErrEncryptionFailed = errors.New("encryption failed") // ErrDecryptionFailed 解密失败 ErrDecryptionFailed = errors.New("decryption failed") // ErrInvalidKey 密钥无效 ErrInvalidKey = errors.New("invalid encryption key") // ErrMarshalFailed JSON 序列化失败 ErrMarshalFailed = errors.New("failed to marshal data") // ErrUnmarshalFailed JSON 反序列化失败 ErrUnmarshalFailed = errors.New("failed to unmarshal data") // ErrServerResponse 服务器响应错误 ErrServerResponse = errors.New("server response error") // ErrClientClosed 客户端已关闭 ErrClientClosed = errors.New("client is closed") // ErrBufferFull 事件缓冲区已满 ErrBufferFull = errors.New("event buffer is full") )
预定义的错误类型
Functions ¶
func AESDecrypt ¶
AESDecrypt 使用 AES-CBC 模式解密数据
参数:
- key: 解密密钥,应与加密时使用的密钥相同
- ciphertextBase64: Base64 编码的密文
返回:
- 解密后的原始数据
- 错误信息(如果解密失败)
Types ¶
type AESClient
deprecated
AESClient 支持 AES 加密的客户端
Deprecated: 推荐使用 Client + WithEncryption 选项替代:
// 旧方式
aesClient := analytics.NewAESClient(url, secretKey)
aesClient.PostEncrypted("/api/events", data)
// 新方式(推荐)
client := analytics.NewClient(url, "MyApp",
analytics.WithEncryption(secretKey))
client.Track("event", properties)
func NewAESClient
deprecated
func (*AESClient) PostEncrypted ¶
PostEncrypted 发送加密的 POST 请求
工作流程:
- 将数据序列化为 JSON
- 使用 AES 加密 JSON 数据
- 发送加密数据到服务器
- 如果服务器返回加密响应,自动解密
参数:
- path: API 路径(如 "/api/events")
- data: 要发送的数据(将被自动加密)
返回:
- 响应数据(如果服务器返回加密数据,已自动解密)
- 错误信息
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client 分析客户端
func NewClient ¶
func NewClient(serverURL, productName string, opts ...ClientOption) *Client
NewClient 创建新的分析客户端
serverURL: 分析服务器地址,例如 "http://localhost:8080" productName: 产品名称,用于区分不同应用 opts: 可选配置项
注意:NewClient 不会自动上报安装信息。如需上报,请调用 client.ReportInstall()
示例:
client := analytics.NewClient("http://localhost:8080", "MyApp")
defer client.Close()
// 可选:上报安装信息
client.ReportInstall()
// 发送事件
client.Track("button_click", map[string]interface{}{"button": "submit"})
func (*Client) ReportInstall ¶
func (c *Client) ReportInstall()
ReportInstall 上报安装信息(异步) 该方法会在后台goroutine中执行,不会阻塞主流程
Example ¶
ExampleClient_ReportInstall 演示如何上报安装信息
package main
import (
"fmt"
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
// 创建客户端
client := analytics.NewClient(
"http://localhost:8080",
"my-awesome-app",
analytics.WithDebug(true),
)
defer client.Close()
// 上报安装信息(异步)
client.ReportInstall()
// 继续执行其他业务逻辑
fmt.Println("安装信息已提交上报")
}
Output: 安装信息已提交上报
func (*Client) ReportInstallWithCallback ¶
ReportInstallWithCallback 上报安装信息并执行回调 适用于需要知道上报结果的场景
Example ¶
ExampleClient_ReportInstallWithCallback 演示带回调的安装信息上报
package main
import (
"log"
"time"
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
client := analytics.NewClient(
"http://localhost:8080",
"my-awesome-app",
)
defer client.Close()
// 上报安装信息并处理结果
client.ReportInstallWithCallback(func(err error) {
if err != nil {
log.Printf("上报安装信息失败: %v", err)
} else {
log.Println("上报安装信息成功")
}
})
// 等待回调执行
time.Sleep(2 * time.Second)
}
func (*Client) Track ¶
Track 发送一个简单事件(异步)
client.Track("button_click", map[string]interface{}{
"button_name": "login",
})
func (*Client) TrackAppExit ¶
TrackAppExit 记录应用退出事件 在应用退出前调用,用于统计会话时长
Example ¶
ExampleClient_TrackAppExit 演示应用退出统计
package main
import (
"fmt"
"time"
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
client := analytics.NewClient(
"http://localhost:8080",
"my-awesome-app",
)
defer client.Close()
// 模拟应用运行
time.Sleep(1 * time.Second)
// 记录应用退出(同步发送,确保数据不丢失)
client.TrackAppExit(map[string]interface{}{
"exit_reason": "user_quit",
})
fmt.Println("应用退出事件已记录")
}
Output: 应用退出事件已记录
func (*Client) TrackAppLaunch ¶
TrackAppLaunch 记录应用启动事件 每次应用启动时调用,用于统计启动次数和启动时间
Example ¶
ExampleClient_TrackAppLaunch 演示应用启动统计
package main
import (
"fmt"
analytics "github.com/difyz9/go-analysis-client"
)
func main() {
client := analytics.NewClient(
"http://localhost:8080",
"my-awesome-app",
analytics.WithDebug(true),
)
defer client.Close()
// 记录应用启动
client.TrackAppLaunch(map[string]interface{}{
"version": "1.0.0",
"build": "100",
"launch_via": "desktop_icon",
})
fmt.Println("应用启动事件已记录")
}
Output: 应用启动事件已记录
func (*Client) TrackEvent
deprecated
TrackEvent 发送分类事件(Google Analytics 风格)
Deprecated: Use Track instead for better flexibility. Migration example:
Old: client.TrackEvent("user", "login", "email", 1)
New: client.Track("user_login", map[string]interface{}{
"category": "user",
"action": "login",
"label": "email",
"value": 1,
})
func (*Client) TrackSync
deprecated
TrackSync 同步发送事件(阻塞直到发送完成)
Deprecated: Use Track followed by Flush for better control. Migration example:
Old: err := client.TrackSync("user_login", properties)
New: client.Track("user_login", properties)
client.Flush()
type ClientError ¶
type ClientError struct {
// Op 是发生错误的操作名称(如 "Track", "Flush", "ReportInstall")
Op string
// Err 是底层错误
Err error
// Context 包含额外的错误上下文信息(可选)
Context map[string]interface{}
}
ClientError 表示客户端操作中发生的错误
它包含了错误发生的操作上下文,便于调试和日志记录。
示例:
err := &ClientError{
Op: "Track",
Err: ErrNetworkTimeout,
}
fmt.Println(err) // Output: Track: network timeout
func (*ClientError) Unwrap ¶
func (e *ClientError) Unwrap() error
Unwrap 返回底层错误,支持 errors.Is 和 errors.As
type ClientOption ¶
type ClientOption func(*Client)
ClientOption 客户端配置选项
func WithEncryption ¶
func WithEncryption(secretKey string) ClientOption
WithEncryption 启用 AES 加密传输 secretKey 必须是 16、24 或 32 字节长度,对应 AES-128、AES-192 或 AES-256
func WithFlushInterval ¶
func WithFlushInterval(interval time.Duration) ClientOption
WithFlushInterval 设置自动刷新间隔
type EncryptionConfig ¶
EncryptionConfig 加密配置
type Event ¶
type Event struct {
Name string `json:"name"`
Timestamp int64 `json:"timestamp"`
Properties map[string]interface{} `json:"properties,omitempty"`
// 可选:Google Analytics 风格分类
Category string `json:"category,omitempty"`
Action string `json:"action,omitempty"`
Label string `json:"label,omitempty"`
Value float64 `json:"value,omitempty"`
}
Event 表示一个分析事件
type InstallInfo ¶
type InstallInfo struct {
Product string `json:"product"` // 产品名称
DeviceID string `json:"device_id"` // 设备ID
Timestamp int64 `json:"timestamp"` // 时间戳
Sign string `json:"sign"` // 签名
// 设备详细信息(可选)
Hostname string `json:"hostname,omitempty"`
OS string `json:"os,omitempty"`
Platform string `json:"platform,omitempty"`
PlatformVersion string `json:"platform_version,omitempty"`
KernelVersion string `json:"kernel_version,omitempty"`
KernelArch string `json:"kernel_arch,omitempty"`
Uptime uint64 `json:"uptime,omitempty"`
}
InstallInfo 安装信息
type NetworkError ¶
type NetworkError struct {
// Op 是 HTTP 操作(GET, POST 等)
Op string
// URL 是请求的完整 URL
URL string
// StatusCode 是 HTTP 状态码(如果有响应)
StatusCode int
// Err 是底层错误
Err error
// Retryable 指示该错误是否可以重试
Retryable bool
}
NetworkError 表示网络请求相关的错误
包含了请求的详细信息,便于重试和诊断。
示例:
err := &NetworkError{
Op: "POST",
URL: "http://example.com/api/events",
StatusCode: 500,
Err: ErrServerResponse,
}