analytics

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2025 License: MIT Imports: 17 Imported by: 1

README

Go Analysis Client

Go Reference Go Report Card

Go Analysis Client 是一个轻量级、高性能的 Go 语言数据分析 SDK,支持事件追踪、用户行为分析和业务数据收集。

特性

  • 🚀 高性能: 异步事件上报,不影响主业务性能
  • 🔒 安全加密: 支持 AES 加密保护数据传输
  • 📊 丰富事件: 支持自定义事件、用户事件、设备信息等
  • 🎯 批量上报: 支持事件批量上报,提高传输效率
  • 🛡️ 错误处理: 完善的错误处理和重试机制
  • 📱 多平台: 支持 Web、移动端、服务端等多种场景
  • 📈 安装统计: 自动收集安装信息和应用生命周期数据
  • 🔄 会话管理: 自动管理用户会话和设备识别

快速开始

安装
go get github.com/difyz9/go-analysis-client
基础使用(30 秒快速开始)
package main

import (
    "log"
    analytics "github.com/difyz9/go-analysis-client"
)

func main() {
    // 1. 创建客户端
    client := analytics.NewClient(
        "http://localhost:8080",  // 服务器地址
        "MyApp",                  // 产品名称
        analytics.WithDebug(true),
    )
    defer client.Close()

    // 2. 可选:上报安装信息
    client.ReportInstall()

    // 3. 发送事件
    client.Track("user_login", map[string]interface{}{
        "platform": "web",
        "version":  "1.0.0",
    })

    log.Println("事件已发送!")
}
完整示例(包含生命周期)
package main

import (
    analytics "github.com/difyz9/go-analysis-client"
)

func main() {
    // 创建客户端
    client := analytics.NewClient(
        "http://localhost:8080",
        "MyApp",
        analytics.WithDebug(true),
        analytics.WithUserID("user123"),
    )
    
    // 确保退出时发送剩余事件
    defer func() {
        client.TrackAppExit(map[string]interface{}{
            "exit_reason": "normal",
        })
        client.Close()
    }()

    // 上报安装信息(可选)
    client.ReportInstall()

    // 记录应用启动
    client.TrackAppLaunch(map[string]interface{}{
        "version": "1.0.0",
    })

    // 发送业务事件
    client.Track("button_click", map[string]interface{}{
        "button": "submit",
        "screen": "home",
    })
}

详细文档

配置选项
config := analytics.Config{
    ServerURL:     "https://analytics.example.com",  // 必填:分析服务器地址
    ProductID:     "your-product-id",                // 必填:产品ID
    APIKey:        "your-api-key",                   // 必填:API密钥
    Timeout:       30 * time.Second,                 // 可选:请求超时时间
    BatchSize:     50,                               // 可选:批量上报大小
    FlushInterval: 5 * time.Second,                  // 可选:刷新间隔
    EnableEncryption: true,                          // 可选:启用加密
    EncryptionKey:    "your-32-byte-encryption-key", // 可选:加密密钥
}
事件类型
基础事件
event := analytics.Event{
    Name:       "page_view",
    UserID:     "user123",
    SessionID:  "session456",
    Timestamp:  time.Now(),
    Properties: map[string]interface{}{
        "page": "/dashboard",
        "referrer": "https://google.com",
    },
}
用户事件
userEvent := analytics.UserEvent{
    UserID:    "user123",
    Action:    "login",
    Timestamp: time.Now(),
    UserProperties: map[string]interface{}{
        "name":     "张三",
        "email":    "zhangsan@example.com",
        "plan":     "premium",
        "created":  "2023-01-01",
    },
}
设备信息
device := analytics.DeviceInfo{
    DeviceID:      "device123",
    Platform:      "web",
    OSName:        "macOS",
    OSVersion:     "13.0",
    AppVersion:    "1.2.0",
    Language:      "zh-CN",
    Timezone:      "Asia/Shanghai",
    ScreenSize:    "1920x1080",
    UserAgent:     "Mozilla/5.0...",
}
批量上报
events := []analytics.Event{
    {Name: "event1", UserID: "user1"},
    {Name: "event2", UserID: "user2"},
    {Name: "event3", UserID: "user3"},
}

err := client.TrackBatch(events)
if err != nil {
    log.Printf("批量上报失败: %v", err)
}
加密传输

启用加密可以保护敏感数据:

config := analytics.Config{
    ServerURL:        "https://analytics.example.com",
    ProductID:        "your-product-id",
    APIKey:          "your-api-key",
    EnableEncryption: true,
    EncryptionKey:    "your-32-byte-encryption-key-here!",
}
错误处理
client.SetErrorHandler(func(err error) {
    log.Printf("Analytics错误: %v", err)
    // 可以发送到错误监控系统
})

高级使用

自定义HTTP客户端
httpClient := &http.Client{
    Timeout: 30 * time.Second,
    Transport: &http.Transport{
        MaxIdleConns:       10,
        IdleConnTimeout:    30 * time.Second,
        DisableCompression: true,
    },
}

config.HTTPClient = httpClient
中间件支持

对于Web应用,可以使用中间件自动收集请求信息:

// Gin框架示例
func AnalyticsMiddleware(client *analytics.Client) gin.HandlerFunc {
    return func(c *gin.Context) {
        start := time.Now()
        c.Next()
        
        // 记录请求事件
        client.Track(analytics.Event{
            Name: "api_request",
            Properties: map[string]interface{}{
                "method":      c.Request.Method,
                "path":        c.Request.URL.Path,
                "status_code": c.Writer.Status(),
                "duration":    time.Since(start).Milliseconds(),
                "user_agent":  c.Request.UserAgent(),
                "ip":          c.ClientIP(),
            },
        })
    }
}

示例项目

API 参考

推荐 API

我们推荐使用以下核心 API,它们简洁、灵活且功能完整:

🎯 事件追踪
// 推荐:使用 Track 发送所有事件(异步,高性能)
client.Track("user_login", map[string]interface{}{
    "method": "email",
    "platform": "web",
})

// 如需同步等待:使用 Track + Flush
client.Track("critical_event", properties)
client.Flush()  // 等待所有事件发送完成
📦 批量发送
// 批量发送多个事件
client.TrackBatch([]analytics.Event{
    {Name: "event1", Properties: map[string]interface{}{"key": "value1"}},
    {Name: "event2", Properties: map[string]interface{}{"key": "value2"}},
})
已废弃 API

以下方法仍然可用以保持向后兼容,但不推荐在新代码中使用:

  • ⚠️ TrackEvent(category, action, label, value) - 已废弃,请使用 Track 替代
  • ⚠️ TrackSync(eventName, properties) - 已废弃,请使用 Track + Flush 替代
完整方法列表
  • NewClient(serverURL, productName string, opts ...ClientOption) *Client - 创建客户端
  • Track(eventName string, properties map[string]interface{}) - 推荐:发送事件(异步)
  • TrackBatch(events []Event) - 推荐:批量发送事件
  • Flush() - 推荐:立即刷新缓冲区
  • ReportInstall() - 上报安装信息(异步)
  • ReportInstallWithCallback(callback func(error)) - 上报安装信息并回调
  • TrackAppLaunch(properties map[string]interface{}) - 记录应用启动
  • TrackAppExit(properties map[string]interface{}) - 记录应用退出
  • SetUserID(userID string) - 设置用户ID
  • GetDeviceID() string - 获取设备ID
  • GetSessionID() string - 获取会话ID
  • Close() - 关闭客户端
配置结构
type Config struct {
    ServerURL        string        // 服务器地址
    ProductID        string        // 产品ID
    APIKey           string        // API密钥
    Timeout          time.Duration // 请求超时
    BatchSize        int           // 批量大小
    FlushInterval    time.Duration // 刷新间隔
    EnableEncryption bool          // 启用加密
    EncryptionKey    string        // 加密密钥
    HTTPClient       *http.Client  // HTTP客户端
}

最佳实践

  1. 性能优化

    • 使用批量上报减少网络请求
    • 设置合适的刷新间隔
    • 避免在高频场景中同步发送事件
  2. 错误处理

    • 设置错误处理器记录失败事件
    • 实现重试机制
    • 监控上报成功率
  3. 数据安全

    • 启用加密传输保护敏感数据
    • 定期轮换API密钥
    • 避免在客户端存储敏感信息
  4. 事件设计

    • 使用清晰的事件名称
    • 保持属性结构一致
    • 避免过度收集用户数据

贡献指南

欢迎贡献代码!请遵循以下步骤:

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add some amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 创建 Pull Request

许可证

本项目使用 MIT 许可证 - 查看 LICENSE 文件了解详情。

支持

更新日志

v1.1.0
  • ✅ 新增安装信息统计功能
  • ✅ 新增应用生命周期跟踪(启动/退出)
  • ✅ 新增会话管理和设备识别
  • ✅ 支持安装信息回调函数
  • ✅ 优化设备ID生成算法
v1.0.0
  • 初始版本发布
  • 支持基础事件追踪
  • 支持批量上报
  • 支持AES加密
  • 支持多种事件类型

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

Examples

Constants

This section is empty.

Variables

View Source
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

func AESDecrypt(key []byte, ciphertextBase64 string) ([]byte, error)

AESDecrypt 使用 AES-CBC 模式解密数据

参数:

  • key: 解密密钥,应与加密时使用的密钥相同
  • ciphertextBase64: Base64 编码的密文

返回:

  • 解密后的原始数据
  • 错误信息(如果解密失败)

func AESEncrypt

func AESEncrypt(key []byte, plaintext []byte) (string, error)

AESEncrypt 使用 AES-CBC 模式加密数据

参数:

  • key: 加密密钥,支持 16/24/32 字节(对应 AES-128/192/256)
  • plaintext: 要加密的原始数据

返回:

  • Base64 编码的密文
  • 错误信息(如果加密失败)

注意: 如果密钥长度不符合要求,会自动调整为最接近的有效长度。

Types

type AESClient deprecated

type AESClient struct {
	BaseURL   string
	SecretKey string
	Client    *http.Client
}

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 NewAESClient(baseURL, secretKey string) *AESClient

NewAESClient 创建新的 AES 客户端

Deprecated: 推荐使用 NewClient + WithEncryption 选项

func (*AESClient) PostEncrypted

func (c *AESClient) PostEncrypted(path string, data interface{}) ([]byte, error)

PostEncrypted 发送加密的 POST 请求

工作流程:

  1. 将数据序列化为 JSON
  2. 使用 AES 加密 JSON 数据
  3. 发送加密数据到服务器
  4. 如果服务器返回加密响应,自动解密

参数:

  • path: API 路径(如 "/api/events")
  • data: 要发送的数据(将被自动加密)

返回:

  • 响应数据(如果服务器返回加密数据,已自动解密)
  • 错误信息

func (*AESClient) PostPlain

func (c *AESClient) PostPlain(path string, data interface{}) ([]byte, error)

PostPlain 发送普通(未加密)的 POST 请求

用于发送不需要加密的数据,或与不支持加密的服务器通信。

参数:

  • path: API 路径
  • 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) Close

func (c *Client) Close() error

Close 关闭客户端,确保所有事件发送完成

func (*Client) Flush

func (c *Client) Flush()

Flush 立即发送所有缓冲的事件

func (*Client) GetDeviceID

func (c *Client) GetDeviceID() string

GetDeviceID 获取当前设备ID

func (*Client) GetSessionID

func (c *Client) GetSessionID() string

GetSessionID 获取当前会话ID

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

func (c *Client) ReportInstallWithCallback(callback func(error))

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) SetUserID

func (c *Client) SetUserID(userID string)

SetUserID 设置用户ID

func (*Client) Track

func (c *Client) Track(eventName string, properties map[string]interface{})

Track 发送一个简单事件(异步)

client.Track("button_click", map[string]interface{}{
    "button_name": "login",
})

func (*Client) TrackAppExit

func (c *Client) TrackAppExit(properties map[string]interface{})

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

func (c *Client) TrackAppLaunch(properties map[string]interface{})

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) TrackBatch

func (c *Client) TrackBatch(events []Event)

TrackBatch 批量发送事件

func (*Client) TrackEvent deprecated

func (c *Client) TrackEvent(category, action, label string, value float64)

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

func (c *Client) TrackSync(eventName string, properties map[string]interface{}) error

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) Error

func (e *ClientError) Error() string

Error 实现 error 接口

func (*ClientError) Unwrap

func (e *ClientError) Unwrap() error

Unwrap 返回底层错误,支持 errors.Is 和 errors.As

type ClientOption

type ClientOption func(*Client)

ClientOption 客户端配置选项

func WithBatchSize

func WithBatchSize(size int) ClientOption

WithBatchSize 设置批量发送大小

func WithBufferSize

func WithBufferSize(size int) ClientOption

WithBufferSize 设置事件缓冲区大小

func WithDebug

func WithDebug(debug bool) ClientOption

WithDebug 启用调试模式

func WithDeviceID

func WithDeviceID(deviceID string) ClientOption

WithDeviceID 设置设备ID

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 设置自动刷新间隔

func WithLogger

func WithLogger(logger Logger) ClientOption

WithLogger 设置自定义日志器

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout 设置HTTP超时

func WithUserID

func WithUserID(userID string) ClientOption

WithUserID 设置用户ID

type EncryptionConfig

type EncryptionConfig struct {
	Enabled   bool
	SecretKey string
}

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 Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

Logger 日志接口

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,
}

func (*NetworkError) Error

func (e *NetworkError) Error() string

Error 实现 error 接口

func (*NetworkError) Unwrap

func (e *NetworkError) Unwrap() error

Unwrap 返回底层错误

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL