// Go 1.22+；只使用标准库。
package main
import (
  "bytes"
  "crypto/hmac"
  "crypto/rand"
  "crypto/sha256"
  "encoding/hex"
  "encoding/json"
  "fmt"
  "net/http"
  "os"
  "strconv"
  "strings"
  "time"
)
func main() {
  baseURL, apiKey, secret := os.Getenv("OPEN_API_BASE_URL"), os.Getenv("OPEN_API_KEY"), os.Getenv("OPEN_API_SECRET")
  if baseURL == "" || apiKey == "" || secret == "" { panic("请设置环境变量") }
  path := "/api/v1/open/watch-data/overview"
  rawBody := []byte("{\"ticketCode\":\"demo-live\",\"playbackMode\":\"ALL\"}")
  nonceBytes := make([]byte, 16)
  if _, err := rand.Read(nonceBytes); err != nil { panic("随机数生成失败") }
  timestamp, nonce := strconv.FormatInt(time.Now().Unix(), 10), hex.EncodeToString(nonceBytes)
  digest := sha256.Sum256(rawBody)
  canonical := strings.Join([]string{apiKey, "POST", path, timestamp, nonce, hex.EncodeToString(digest[:])}, "\n")
  mac := hmac.New(sha256.New, []byte(secret)); mac.Write([]byte(canonical))
  req, err := http.NewRequest("POST", strings.TrimRight(baseURL, "/") + path, bytes.NewReader(rawBody))
  if err != nil { panic("请求构建失败") }
  for name, value := range map[string]string{"Content-Type":"application/json", "X-API-Key":apiKey, "X-Timestamp":timestamp, "X-Nonce":nonce, "X-Signature":hex.EncodeToString(mac.Sum(nil))} { req.Header.Set(name,value) }
  client := &http.Client{Timeout:15*time.Second, CheckRedirect:func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}
  resp, err := client.Do(req)
  if err != nil { panic("网络请求失败，请检查连接") }
  defer resp.Body.Close()
  var result map[string]any
  if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { panic("响应不是 JSON") }
  // result["data"] 交给业务处理；只记录状态和请求编号。
  fmt.Printf("status=%d requestId=%v\n", resp.StatusCode, result["requestId"])
}
