重构: 活动热切换并发安全 + 代码清理优化

- 活动切换并发安全:App/Scheduler 增加 client/cfg 读写锁与快照访问,
  支持运行中热替换客户端,切换活动不再静默覆盖用户自定义 timeApiUrl
- 启动失败时写入崩溃日志文件便于事后排查
- 前端类型声明从 Wails 自动生成的绑定派生,避免手写契约漂移
- 提取 parseAccountFile 消除 ExportAccounts/OrganizeAccounts 重复解析逻辑
- 删除 utils 中未使用的 ReadJSON/WriteJSON/WriteError 及空目录 internal/app
- gofmt 统一格式化(activity/types/scheduler 字段对齐)
- 新增 logger/seckill/utils 单元测试
- 清理 git 中遗留产物(frontend/app.js、yml.txt、其他日志/)并补全 .gitignore
This commit is contained in:
yml2213
2026-07-29 12:33:16 +08:00
parent ed3fd5f09e
commit 3ae9cb4a42
20 changed files with 574 additions and 20390 deletions
+17 -17
View File
@@ -46,15 +46,15 @@ const douyuBase = constants.BaseURL
// peace 精英手册(旧活动,ActAlias=20260120QYOOB)。
var peace = &Activity{
ID: "peace",
DisplayName: "精英手册",
ManualID: "G4KA4Qnz4LDp7",
RoomID: "9263298",
ActAlias: "20260120QYOOB",
BaseURL: douyuBase,
ShopReferer: douyuBase + "/pages/live-peace-handbook/web/shop?ditchname=pass0&roomId=9263298",
StoreHomeURL: douyuBase + "/wgapi/ordnc/activity/peace/storehome?manualID=G4KA4Qnz4LDp7&rid=9263298",
CSRFURL: douyuBase + "/japi/carnival/nc/common/generateCsrf",
ID: "peace",
DisplayName: "精英手册",
ManualID: "G4KA4Qnz4LDp7",
RoomID: "9263298",
ActAlias: "20260120QYOOB",
BaseURL: douyuBase,
ShopReferer: douyuBase + "/pages/live-peace-handbook/web/shop?ditchname=pass0&roomId=9263298",
StoreHomeURL: douyuBase + "/wgapi/ordnc/activity/peace/storehome?manualID=G4KA4Qnz4LDp7&rid=9263298",
CSRFURL: douyuBase + "/japi/carnival/nc/common/generateCsrf",
BatchLimitURL: douyuBase + "/wgapi/ordnc/activity/peace/batchExchangeLimit",
PreExchangeURL: douyuBase + "/wgapi/ordnc/activity/peace/preExchange",
ExchangeURL: douyuBase + "/wgapi/ordnc/activity/peace/exchange",
@@ -68,13 +68,13 @@ var peace = &Activity{
// peacematch 电竞手册(新活动,ActAlias=20260226ZMGDG)。
// 数据来源:/Users/yml/Desktop/抓包/douyu/7.29/电竞手册-基础信息.har 及 7.28 系列抓包。
var peacematch = &Activity{
ID: "peacematch",
DisplayName: "电竞手册",
ManualID: "1W0yGkOdDbAXb",
RoomID: "9263298",
ActAlias: "20260226ZMGDG",
BaseURL: douyuBase,
ShopReferer: douyuBase + "/pages/live-peace-pel/web/shop?roomId=9263298&isAnchorSide=0",
ID: "peacematch",
DisplayName: "电竞手册",
ManualID: "1W0yGkOdDbAXb",
RoomID: "9263298",
ActAlias: "20260226ZMGDG",
BaseURL: douyuBase,
ShopReferer: douyuBase + "/pages/live-peace-pel/web/shop?roomId=9263298&isAnchorSide=0",
StoreHomeURL: douyuBase + "/wgapi/ordnc/activity/peacematch/storehome?manualID=1W0yGkOdDbAXb&rid=9263298",
// generateCsrf 为嘉年华平台级接口,抓包未单独出现,沿用 peace 同款端点。
CSRFURL: douyuBase + "/japi/carnival/nc/common/generateCsrf",
@@ -91,7 +91,7 @@ var peacematch = &Activity{
}
var registry = map[string]*Activity{
peace.ID: peace,
peace.ID: peace,
peacematch.ID: peacematch,
}
+81
View File
@@ -0,0 +1,81 @@
package logger
import (
"testing"
)
func TestIsLogLevel(t *testing.T) {
valid := []string{"success", "error", "warn", "info", "debug", "SUCCESS", "Warn"}
for _, l := range valid {
if !IsLogLevel(l) {
t.Errorf("IsLogLevel(%q) = false, want true", l)
}
}
invalid := []string{"fatal", "trace", "", "warning"}
for _, l := range invalid {
if IsLogLevel(l) {
t.Errorf("IsLogLevel(%q) = true, want false", l)
}
}
}
func TestDetectLogLevel(t *testing.T) {
cases := []struct {
line string
want string
}{
{"[2026/01/01 00:00:00.000][网络][debug] 调试", "debug"},
{"[2026/01/01 00:00:00.000][抢购][success] 兑换成功", "success"},
{"[2026/01/01 00:00:00.000][系统][error] 失败", "error"},
{"[2026/01/01 00:00:00.000][系统][warn] 跳过", "warn"},
{"[2026/01/01 00:00:00.000][系统][info] 信息", "info"},
{"兑换成功完成", "success"},
{"网络请求失败 error 发生", "error"},
{"配置降级处理 warn", "warn"},
{"普通信息日志", "info"},
}
for _, c := range cases {
if got := DetectLogLevel(c.line); got != c.want {
t.Errorf("DetectLogLevel(%q) = %q, want %q", c.line, got, c.want)
}
}
}
func TestParseLogLine(t *testing.T) {
line := "2026/01/01 12:00:00.123 [抢购][success] 账号:testuser 兑换成功"
meta := ParseLogLine(line)
if meta.Time != "2026-01-01 12:00:00.123" {
t.Errorf("ParseLogLine Time = %q, want '2026-01-01 12:00:00.123'", meta.Time)
}
if meta.Category != "抢购" {
t.Errorf("ParseLogLine Category = %q, want '抢购'", meta.Category)
}
if meta.Level != "success" {
t.Errorf("ParseLogLine Level = %q, want 'success'", meta.Level)
}
if meta.Account != "testuser" {
t.Errorf("ParseLogLine Account = %q, want 'testuser'", meta.Account)
}
}
func TestParseLogLineShort(t *testing.T) {
// 不含时间的行,ParseLogLine 不应 panic,Time 应为空
line := "[系统][info] 配置已加载"
meta := ParseLogLine(line)
if meta.Category != "系统" {
t.Errorf("ParseLogLine Category = %q, want '系统'", meta.Category)
}
if meta.Level != "info" {
t.Errorf("ParseLogLine Level = %q, want 'info'", meta.Level)
}
if meta.Time != "" {
t.Errorf("ParseLogLine Time = %q, want empty", meta.Time)
}
}
func TestParseLogMeta(t *testing.T) {
cat, lvl := ParseLogMeta("[网络][warn] 降级")
if cat != "网络" || lvl != "warn" {
t.Errorf("ParseLogMeta = (%q, %q), want ('网络', 'warn')", cat, lvl)
}
}
+53 -15
View File
@@ -54,9 +54,10 @@ type runSettings struct {
// Scheduler 抢购调度器。
type Scheduler struct {
client *client.DouyuClient
paths types.AppPaths
font *truetype.Font
clientMu sync.RWMutex
client *client.DouyuClient
paths types.AppPaths
font *truetype.Font
successImages *image.SuccessImageSaver
@@ -82,8 +83,8 @@ type Scheduler struct {
resyncSchedule *time.Timer
warmupGen int64
warmupsMu sync.RWMutex
warmups map[string]types.WarmupData
warmupsMu sync.RWMutex
warmups map[string]types.WarmupData
warmupRunMu sync.Mutex
attemptCacheMu sync.RWMutex
@@ -128,6 +129,33 @@ func (s *Scheduler) Close() {
}
}
// clientSnapshot 返回当前 client 的指针快照(读锁保护,用于执行期间持有一个稳定引用)。
func (s *Scheduler) clientSnapshot() *client.DouyuClient {
s.clientMu.RLock()
defer s.clientMu.RUnlock()
return s.client
}
// UpdateClient 热替换底层 HTTP 客户端(用于活动切换)。
// 若有抢购任务正在运行则拒绝替换,返回 false。
func (s *Scheduler) UpdateClient(newClient *client.DouyuClient) bool {
s.runMu.Lock()
if s.running {
s.runMu.Unlock()
return false
}
s.runMu.Unlock()
s.clientMu.Lock()
defer s.clientMu.Unlock()
old := s.client
s.client = newClient
if old != nil && old.HTTPClient != nil {
old.HTTPClient.CloseIdleConnections()
}
return true
}
// UpdateProducts 更新商品缓存,抢购成功图片会优先使用中文商品名。
func (s *Scheduler) UpdateProducts(products []types.Product) {
next := make(map[string]types.Product, len(products))
@@ -817,6 +845,7 @@ func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) {
logger.LogEvent("预热", "info", "开始预热: %d 个请求", len(attempts))
settings := s.settingsSnapshot()
cli := s.clientSnapshot()
limit := make(chan struct{}, settings.concurrency)
var wg sync.WaitGroup
for _, attempt := range attempts {
@@ -827,12 +856,12 @@ func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) {
defer func() { <-limit }()
start := time.Now()
csrf, err := s.client.GenerateCSRF(attempt.Account.Cookie)
csrf, err := cli.GenerateCSRF(attempt.Account.Cookie)
if err != nil {
logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "CSRF预热失败: 账号=%s 商品=%s err=%v", attempt.Account.Name, attempt.Product.CommodityName, err)
return
}
roleName, err := s.client.RoleName(attempt.Account.Cookie)
roleName, err := cli.RoleName(attempt.Account.Cookie)
if err != nil {
logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "角色预热失败: 账号=%s err=%v", attempt.Account.Name, err)
}
@@ -867,7 +896,8 @@ func uniqueWarmupAttempts(attempts []types.ExchangeAttempt) []types.ExchangeAtte
}
func (s *Scheduler) calibrateDouyuTime(label string) types.TimeCalibration {
calibration, err := s.client.BestServerTimeCalibration(timeCalibrateRounds, timeCalibrateWait)
cli := s.clientSnapshot()
calibration, err := cli.BestServerTimeCalibration(timeCalibrateRounds, timeCalibrateWait)
if err != nil {
logger.LogEvent("时间", "warn", "%s校准降级: %v", label, err)
}
@@ -906,6 +936,7 @@ func (s *Scheduler) stopSchedulesLocked() {
}
func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResult {
cli := s.clientSnapshot()
result := types.ExchangeResult{
Account: attempt.Account.Name,
Product: attempt.Product.CommodityName,
@@ -922,7 +953,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
}
if csrf == "" {
var err error
csrf, err = s.client.GenerateCSRF(attempt.Account.Cookie)
csrf, err = cli.GenerateCSRF(attempt.Account.Cookie)
if err != nil {
result.Message = "失败|生成CSRF失败: " + err.Error()
return result
@@ -930,7 +961,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "CSRF已生成,本次兑换链路复用同一个 token: 账号=%s 商品=%s", attempt.Account.Name, attempt.Product.CommodityName)
}
limit, err := s.client.BatchExchangeLimit(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
limit, err := cli.BatchExchangeLimit(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
if err != nil {
result.Message = "失败|批量限制检查失败: " + err.Error()
return result
@@ -941,7 +972,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
}
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "批量限制通过: 账号=%s 商品=%s limit=%d", attempt.Account.Name, attempt.Product.CommodityName, limit)
if err := s.client.PreExchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf); err != nil {
if err := cli.PreExchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf); err != nil {
result.Message = "失败|预兑换失败: " + err.Error()
return result
}
@@ -953,7 +984,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
})
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "资格预检通过: 账号=%s 商品=%s,后续可直兑", attempt.Account.Name, attempt.Product.CommodityName)
exchangeInfo, err := s.client.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
exchangeInfo, err := cli.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
if err != nil {
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
CSRF: csrf,
@@ -967,7 +998,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
}
if roleName == "" {
roleName, err = s.client.RoleName(attempt.Account.Cookie)
roleName, err = cli.RoleName(attempt.Account.Cookie)
if err != nil {
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err)
}
@@ -994,6 +1025,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
// runAttemptFast 激进模式的兑换逻辑,复用缓存的 CSRF,跳过 BatchExchangeLimit 和 PreExchange。
func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.ExchangeResult {
cli := s.clientSnapshot()
result := types.ExchangeResult{
Account: attempt.Account.Name,
Product: attempt.Product.CommodityName,
@@ -1014,7 +1046,7 @@ func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.Exchange
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "激进模式直兑: 账号=%s 商品=%s 第%d包", attempt.Account.Name, attempt.Product.CommodityName, attempt.Index)
// 直接调用 Exchange
exchangeInfo, err := s.client.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
exchangeInfo, err := cli.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
if err != nil {
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
CSRF: csrf,
@@ -1040,7 +1072,7 @@ func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.Exchange
}
if roleName == "" {
var err error
roleName, err = s.client.RoleName(attempt.Account.Cookie)
roleName, err = cli.RoleName(attempt.Account.Cookie)
if err != nil {
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err)
}
@@ -1143,10 +1175,16 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (map[string]any, error
time.Now().Add(resyncRemain).In(constants.CST).Format("15:04:05.000"),
)
remainSecond := int(triggerTime.Sub(serverTime).Seconds())
if remainSecond < 0 {
remainSecond = 0
}
return map[string]any{
"success": true,
"targetTime": targetTime.In(constants.CST).Format("2006-01-02 15:04:05"),
"triggerTime": triggerTime.In(constants.CST).Format("2006-01-02 15:04:05"),
"remainSecond": remainSecond,
"offsetMs": calibration.Offset.Milliseconds(),
"errorBoundMs": calibration.ErrorBound.Milliseconds(),
"rttMs": calibration.RTT.Milliseconds(),
+162
View File
@@ -0,0 +1,162 @@
package seckill
import (
"testing"
"time"
"douyu_go/internal/types"
)
func makeAttempts(names ...string) []types.ExchangeAttempt {
out := make([]types.ExchangeAttempt, 0, len(names))
for i, n := range names {
out = append(out, types.ExchangeAttempt{
Account: types.Account{Name: n},
Index: i + 1,
})
}
return out
}
func TestRetryIntervalFor(t *testing.T) {
stages := []types.RetryStage{
{MaxElapsed: 4, Interval: 120},
{MaxElapsed: 12, Interval: 200},
{MaxElapsed: 30, Interval: 500},
{MaxElapsed: 75, Interval: 1000},
}
cases := []struct {
elapsed time.Duration
want time.Duration
}{
{1 * time.Second, 120 * time.Millisecond},
{5 * time.Second, 200 * time.Millisecond},
{13 * time.Second, 500 * time.Millisecond},
{31 * time.Second, 1000 * time.Millisecond},
{100 * time.Second, 900 * time.Millisecond}, // 超出所有阶段,用默认值
}
for _, c := range cases {
if got := retryIntervalFor(stages, c.elapsed); got != c.want {
t.Errorf("retryIntervalFor(%v) = %v, want %v", c.elapsed, got, c.want)
}
}
}
func TestRetryIntervalForEmpty(t *testing.T) {
// 空阶段或无效阶段都回退到默认 900ms
if got := retryIntervalFor(nil, 1*time.Second); got != 900*time.Millisecond {
t.Errorf("retryIntervalFor(nil) = %v, want 900ms", got)
}
if got := retryIntervalFor([]types.RetryStage{{MaxElapsed: 0, Interval: 0}}, 1*time.Second); got != 900*time.Millisecond {
t.Errorf("retryIntervalFor(invalid) = %v, want 900ms", got)
}
}
func TestRetryCooldownDuration(t *testing.T) {
cases := []struct {
msg string
want time.Duration
}{
{"用户行为异常,请稍后再试", behaviorCooldown},
{"点击太快了", clickFastCooldown},
{"操作频繁请稍后", behaviorCooldown},
{"请求过多", behaviorCooldown},
{"请求太频繁", behaviorCooldown},
{"兑换成功", 0},
{"库存不足", 0},
}
for _, c := range cases {
if got := retryCooldownDuration(c.msg); got != c.want {
t.Errorf("retryCooldownDuration(%q) = %v, want %v", c.msg, got, c.want)
}
}
}
func TestClassifyRetryStop(t *testing.T) {
acc, prod, reason := classifyRetryStop("您已达本次活动兑换上限")
if !acc || prod || reason != "已达兑换上限" {
t.Errorf("classifyRetryStop(兑换上限) = (%v,%v,%q), want (true,false,'已达兑换上限')", acc, prod, reason)
}
acc, prod, reason = classifyRetryStop("未绑定账号")
if !acc || prod || reason != "账号未绑定角色" {
t.Errorf("classifyRetryStop(未绑定) = (%v,%v,%q), want (true,false,'账号未绑定角色')", acc, prod, reason)
}
acc, prod, reason = classifyRetryStop("需要开通精英手册")
if !acc || prod || reason != "账号不满足精英手册条件" {
t.Errorf("classifyRetryStop(精英手册) = (%v,%v,%q), want (true,false,'账号不满足精英手册条件')", acc, prod, reason)
}
// 库存耗尽不停止
acc, prod, reason = classifyRetryStop("商品本次活动库存已耗完")
if acc || prod || reason != "" {
t.Errorf("classifyRetryStop(库存耗完) = (%v,%v,%q), want (false,false,'')", acc, prod, reason)
}
// 普通错误不停止
acc, prod, reason = classifyRetryStop("网络超时")
if acc || prod || reason != "" {
t.Errorf("classifyRetryStop(普通错误) = (%v,%v,%q), want (false,false,'')", acc, prod, reason)
}
}
func TestFilterCooldownAttempts(t *testing.T) {
attempts := makeAttempts("a", "b", "c")
now := time.Now()
cooldown := map[string]time.Time{
"a": now.Add(5 * time.Second), // 仍在冷却
"b": now.Add(-5 * time.Second), // 已过期
}
out, nextReady := filterCooldownAttempts(attempts, cooldown, now)
if len(out) != 2 {
t.Fatalf("filterCooldownAttempts out length = %d, want 2", len(out))
}
for _, a := range out {
if a.Account.Name == "a" {
t.Errorf("account 'a' should be filtered out")
}
}
if nextReady.IsZero() {
t.Errorf("nextReady should not be zero")
}
if !nextReady.After(now) {
t.Errorf("nextReady should be after now")
}
}
func TestPickRoundAttempts(t *testing.T) {
// 账号 A 有 3 个包,账号 B 有 3 个包
attempts := []types.ExchangeAttempt{
{Account: types.Account{Name: "A"}, Index: 1},
{Account: types.Account{Name: "A"}, Index: 2},
{Account: types.Account{Name: "A"}, Index: 3},
{Account: types.Account{Name: "B"}, Index: 1},
{Account: types.Account{Name: "B"}, Index: 2},
{Account: types.Account{Name: "B"}, Index: 3},
}
// 第 1 轮每账号选第 1 包
out := pickRoundAttempts(attempts, 1, 3)
if len(out) != 2 {
t.Fatalf("pickRoundAttempts round1 length = %d, want 2", len(out))
}
for _, a := range out {
if a.Index != 1 {
t.Errorf("round1 should pick index 1, got %d for %s", a.Index, a.Account.Name)
}
}
// 第 2 轮每账号选第 2 包
out = pickRoundAttempts(attempts, 2, 3)
for _, a := range out {
if a.Index != 2 {
t.Errorf("round2 should pick index 2, got %d for %s", a.Index, a.Account.Name)
}
}
// attemptsPerAccount=0 时回退取各自首个
out = pickRoundAttempts(attempts, 1, 0)
for _, a := range out {
if a.Index != 1 {
t.Errorf("round with 0 perAccount should pick index 1, got %d", a.Index)
}
}
// 空输入
if out := pickRoundAttempts(nil, 1, 3); out != nil {
t.Errorf("pickRoundAttempts(nil) = %v, want nil", out)
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ import (
// Config 应用配置。
type Config struct {
TimeAPIURL string `json:"timeApiUrl"`
Activity string `json:"activity"` // 当前活动 ID,见 internal/activity
Activity string `json:"activity"` // 当前活动 ID,见 internal/activity
TraceEnabled bool `json:"traceEnabled"`
TraceMaxBody int `json:"traceMaxBody"`
LogLevel string `json:"logLevel"` // debug / info / warn / error
-24
View File
@@ -1,9 +1,7 @@
package utils
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
@@ -116,25 +114,3 @@ func MaskValue(value string) string {
func RoundDuration(d time.Duration) time.Duration {
return d.Round(time.Millisecond)
}
// ReadJSON 读取请求 JSON。
func ReadJSON(r *http.Request, out any) error {
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(out)
}
// WriteJSON 写出 JSON 响应。
func WriteJSON(w http.ResponseWriter, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(value)
}
// WriteError 写出统一错误 JSON,同时设置 HTTP 状态码。
func WriteError(w http.ResponseWriter, status int, err error) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]any{
"success": false,
"error": err.Error(),
})
}
+117
View File
@@ -0,0 +1,117 @@
package utils
import (
"strings"
"testing"
)
func TestMaskValue(t *testing.T) {
cases := []struct {
in string
want string
}{
{"", "****"},
{"abc", "****"},
{"12345678", "****"},
{"abcdefghij", "abcd****ghij"}, // 10 runes => 前4+****+后4
}
for _, c := range cases {
got := MaskValue(c.in)
if got != c.want {
t.Errorf("MaskValue(%q) = %q, want %q", c.in, got, c.want)
}
}
}
func TestMaskCookie(t *testing.T) {
// 空
if got := MaskCookie(""); got != "" {
t.Errorf("MaskCookie(empty) = %q, want empty", got)
}
// 单条
got := MaskCookie("acf_ccn=abcdefghij")
if !strings.Contains(got, "acf_ccn=abcd****ghij") {
t.Errorf("MaskCookie single = %q, want masked acf_ccn", got)
}
// 多条只显示前 3 条并标注总数
got = MaskCookie("a=abcdefghij; b=abcdefghij; c=abcdefghij; d=abcdefghij")
if !strings.Contains(got, "共4项") {
t.Errorf("MaskCookie multi = %q, want '共4项'", got)
}
if strings.Count(got, "; ") > 3 {
t.Errorf("MaskCookie multi shows too many pairs: %q", got)
}
// 缺失 = 号的段被跳过
got = MaskCookie("broken; valid=12345678")
if strings.Contains(got, "broken") {
t.Errorf("MaskCookie should skip pair without '=': %q", got)
}
}
func TestMergeCookie(t *testing.T) {
// 覆盖已有
got := MergeCookie("a=1; b=2; c=3", "b", "20")
if got != "a=1; b=20; c=3" {
t.Errorf("MergeCookie overwrite = %q, want 'a=1; b=20; c=3'", got)
}
// 追加新字段
got = MergeCookie("a=1", "b", "2")
if got != "a=1; b=2" {
t.Errorf("MergeCookie append = %q, want 'a=1; b=2'", got)
}
// 空值不追加
got = MergeCookie("a=1", "b", "")
if got != "a=1" {
t.Errorf("MergeCookie empty value = %q, want 'a=1'", got)
}
// 空值覆盖已有:当前实现对空值仍保留 name= 形式(生产调用均传非空值)
got = MergeCookie("a=1; b=2", "a", "")
if got != "a=; b=2" {
t.Errorf("MergeCookie empty overwrite = %q, want 'a=; b=2'", got)
}
}
func TestSafeFilename(t *testing.T) {
got := SafeFilename("a/b:c*d?e\"f<g>h|i")
want := "a_b_c_d_e_f_g_h_i"
if got != want {
t.Errorf("SafeFilename = %q, want %q", got, want)
}
}
func TestCloneStringMap(t *testing.T) {
in := map[string]string{"a": "1", "b": "2"}
out := CloneStringMap(in)
out["a"] = "changed"
if in["a"] != "1" {
t.Errorf("CloneStringMap should be independent, original mutated")
}
if len(out) != 2 {
t.Errorf("CloneStringMap length = %d, want 2", len(out))
}
}
func TestTrimForLog(t *testing.T) {
if got := TrimForLog("hello", 10); got != "hello" {
t.Errorf("TrimForLog short = %q, want 'hello'", got)
}
got := TrimForLog("abcdefghij", 5)
if got != "abcde..." {
t.Errorf("TrimForLog long = %q, want 'abcde...'", got)
}
if got := TrimForLog(" spaced ", 10); got != "spaced" {
t.Errorf("TrimForLog trim = %q, want 'spaced'", got)
}
}
func TestEmptyDefault(t *testing.T) {
if got := EmptyDefault("", "fb"); got != "fb" {
t.Errorf("EmptyDefault empty = %q, want 'fb'", got)
}
if got := EmptyDefault("x", "fb"); got != "x" {
t.Errorf("EmptyDefault non-empty = %q, want 'x'", got)
}
if got := EmptyDefault(" ", "fb"); got != "fb" {
t.Errorf("EmptyDefault whitespace = %q, want 'fb'", got)
}
}