You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
wt-game/point/README.md

9.1 KiB

point - TapDB事件上报SDK / TapDB Event Reporting SDK

中文 | English


中文

📖 简介

point 是专为TapDB设计的线程安全事件上报SDK提供简洁的API接口和并发安全机制。采用单例模式设计内置HTTP连接池和自动重试策略适用于高并发场景下的数据上报。

GitHub地址: gitea.weitiangame.com/sdk/wt-game/point

📦 安装

go get gitea.weitiangame.com/sdk/wt-game/point

🚀 快速开始

初始化上报器

package main

import (
	"gitea.weitiangame.com/sdk/wt-game/point"
	"go.uber.org/zap"
)

func main() {
	logger, _ := zap.NewProduction()

	// 创建单例上报实例自动注入client_id
	// client_id 请在TapDB控制台获取
	// logger 为zap.Logger实例可选, 用于记录日志, 也可传nil不记录
	reporter := point.New("your_client_id", logger)
}

基础事件上报

   func main() {
         logger, _ := zap.NewProduction()
         reporter := point.New("game_123", logger)
         // 事件数据, 具体字段请参考TapDB文档
         // 文档地址:https://docs.tapdb.com/zh/collecting-data/sdk/ios-sdk
         eventData := map[string]interface{}{
         "name":    "charge",       // 事件名,固定为 charge
         "user_id": "your-user-id", // 必需。用户 ID。必须和 SDK 的 setUser 接口传递的 userId 一样,并且该用户已经通过 SDK 接口进行过推送
         "type":    "track", // 必需。数据类型,请确保传入的值为 track
         "properties": map[string]interface{}{
         "ip":                      "8.8.8.8", // 可选。充值用户的 IP
         "order_id":                "100000",  // 可选。长度大于 0 并小于等于 256。订单 ID。
         "amount":                  100, // 必需。大于 0 并小于等于 100000000000。充值金额。单位分即无论什么币种都需要乘以 100
         "virtual_currency_amount": 100, //获赠虚拟币数量,必传,可为 0
         "currency_type":           "CNY",     // 可选。货币类型。国际通行三字母表示法,为空时默认 CNY。参考人民币 CNY美元 USD欧元 EUR
         "product":                 "item1",   // 可选。长度大于 0 并小于等于 256。商品名称
         "payment":                 "alipay", // 可选。长度大于 0 并小于等于 256。充值渠道
         },
   }

      if resp, err := reporter.Event(eventData); err != nil {
        logger.Error("上报失败", zap.Error(err))
      } else {
            logger.Info("上报成功",
            zap.Int("status", resp.StatusCode()),
            zap.String("trace_id", resp.Header().Get("X-Trace-Id")))
      }
}

🔧 高级用法

启用调试模式

func main() {
// 初始化时启用调试和CURL输出
reporter := point.New("client_123", logger).
Debug().  // 打印显示请求详情
Curl()    // 打印生成CURL命令

reporter.Event(map[string]interface{}{
"event": "ad_click",
"properties": map[string]interface{}{
"ad_id": "banner_001",
},
})
}

自定义HTTP客户端

func main() {
// 创建自定义HTTP客户端, 可以设置超时时间和重试次数具体参数请参考ahttp库
customClient := ahttp.New(&ahttp.Config{
Timeout:   10 * time.Second,
Retries:   3,
}).Client()

point.New("game_123", logger).
SetClient(customClient).  // 注入自定义客户端
Event(eventData)
}

核心特性

特性 描述
单例模式 全局唯一实例,避免重复创建资源
线程安全 基于互斥锁保护配置变更内置线程安全HTTP客户端
调试支持 支持请求详情输出和CURL命令生成
自动重试 依赖底层HTTP客户端的重试策略默认3次

⚠️ 注意事项

  1. New() 方法为单例模式,首次调用后配置不可变更
  2. Debug()Curl() 建议仅在开发环境使用
  3. 事件数据需包含 event 字段,建议包含 distinct_id 字段
  4. HTTP响应状态码非2xx时需要检查请求参数
  5. 上报数据量较大时建议批量处理

🤝 参与贡献

贡献指南 | 提交Issue


English

📖 Introduction

point is a thread-safe event reporting SDK designed for TapDB, providing a simple API and concurrency-safe mechanisms. Built with a singleton pattern, it includes an HTTP connection pool and automatic retry policies, suitable for high-concurrency data reporting scenarios.

GitHub URL: gitea.weitiangame.com/sdk/wt-game/point

📦 Installation

go get gitea.weitiangame.com/sdk/wt-game/point

🚀 Quick Start

Initialize Reporter

package main

import (
    "gitea.weitiangame.com/sdk/wt-game/point"
    "go.uber.org/zap"
)

func main() {
    logger, _ := zap.NewProduction()
    
    // Create a singleton reporter (auto-injects client_id)
    // client_id should be obtained from the TapDB console
    // logger is an optional zap.Logger instance; pass nil to disable logging
    reporter := point.New("your_client_id", logger)
}

Basic Event Reporting

func main() {
    logger, _ := zap.NewProduction()
    reporter := point.New("game_123", logger)
    
    // Event data structure, refer to TapDB documentation for specific fields
    // Documentation: https://docs.tapdb.com/en/collecting-data/sdk/ios-sdk
    eventData := map[string]interface{}{
        "name":    "charge",       // Event name, fixed as 'charge'
        "user_id": "your-user-id", // Required. User ID, must match the userId set via SDK's setUser interface
        "type":    "track",        // Required. Data type, must be 'track'
        "properties": map[string]interface{}{
            "ip":                      "8.8.8.8", // Optional. User's IP address
            "order_id":                "100000",  // Optional. Order ID (length <= 256)
            "amount":                  100,       // Required. Amount in cents (must be > 0)
            "virtual_currency_amount": 100,       // Required. Virtual currency received (can be 0)
            "currency_type":           "CNY",     // Optional. Currency code (default: CNY)
            "product":                 "item1",   // Optional. Product name (length <= 256)
            "payment":                 "alipay",  // Optional. Payment method (length <= 256)
        },
    }

    if resp, err := reporter.Event(eventData); err != nil {
        logger.Error("Report failed", zap.Error(err))
    } else {
        logger.Info("Report succeeded", 
            zap.Int("status", resp.StatusCode()),
            zap.String("trace_id", resp.Header().Get("X-Trace-Id")))
    }
}

🔧 Advanced Usage

Enable Debug Mode

func main() {
    // Enable debug features during initialization
    reporter := point.New("client_123", logger).
        Debug().  // Print request details
        Curl()    // Generate CURL commands for debugging
    
    reporter.Event(eventData)
}

Custom HTTP Client

func main() {
    // Create a custom HTTP client with specific timeout and retry settings
    // Refer to the ahttp library documentation for configuration details
    customClient := ahttp.New(&ahttp.Config{
        Timeout:   10 * time.Second,
        Retries:   3,
    }).Client()

    point.New("game_123", logger).
        SetClient(customClient).  // Inject custom client
        Event(eventData)
}

Key Features

Feature Description
Singleton Single global instance prevents resource duplication
Thread-Safe Mutex-protected configuration with built-in thread-safe HTTP client
Debug Support Request detail logging and CURL command generation
Auto Retry Built-in retry policy (default 3 attempts) via underlying HTTP client

⚠️ Important Notes

  1. The New() method uses singleton pattern; configurations are immutable after the first call
  2. Use Debug() and Curl() only in development environments
  3. Event data must contain required fields as per TapDB documentation. For example:
    • user_id is required for user-related events
    • type must be set to track for tracking events
  4. Check request parameters if receiving non-2xx HTTP responses
  5. Implement batch processing when reporting large volumes of data

🤝 Contributing

Contribution Guide | Open an Issue

⬆ Back to Top