refactor: 后端代码优化 11 项(codestable/refactors/2026-04-25-backend-cleanup)

- 提取 getWKFromContext 辅助函数,消除 handler 中 5 处重复代码
- 提取 retryCode 函数,消除 Login/performStudy 中验证码重试重复
- 提取 removeSession 内部方法,消除 Del/ClearAll/ClearExpired 中 3 处重复
- 提取 WK.UserKey() 方法,消除 4 处 userKey 手动拼接
- SessionManager.Get() 改用 RLock 优化读性能
- GetRecords 递归分页改为迭代,避免栈溢出
- prepareRequestClient 添加配置缓存,仅在 debug 设置变化时重建
- 修正 schedule.go 时区为 Asia/Shanghai + cron "0 6 * * *"
- 修正 typo "以达到" → "已达到"
- 删除未使用的 QAList struct
- 修复 bufferHub.append 切片内存泄漏

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-26 13:07:45 +08:00
parent 2a6732ffe7
commit 536aa506f9
9 changed files with 488 additions and 94 deletions

View File

@@ -25,7 +25,7 @@ const (
StudyStart StudyStatus = 1 // 开始学习
Study StudyStatus = 2 // 学习中
StudyOver StudyStatus = 3 // 学习介绍
StudyOver StudyStatus = 3 // 学习结束
)
// User: 用户
@@ -49,11 +49,36 @@ type Course struct {
Type string `json:"type"`
}
type QAList struct {
}
// GetRecords 分页获取记录(迭代实现)
func GetRecords[T any](wk *WK, rType RecordType, courseID, page string) (*AllRecordResp[T], error) {
log.Debug("获取记录信息", zap.String("host", wk.Host), zap.String("type", string(rType)))
result, err := fetchRecordPage[T](wk, rType, courseID, page)
if err != nil {
return nil, err
}
if !result.Status {
return &result, fmt.Errorf("接口报错: %s", result.Msg)
}
for result.PageInfo.Page < result.PageInfo.PageCount {
nextPage := fmt.Sprint(result.PageInfo.Page + 1)
nextResult, err := fetchRecordPage[T](wk, rType, courseID, nextPage)
if err != nil {
return nil, err
}
result.List = append(result.List, nextResult.List...)
log.Debug("Page", zap.Int("currentPage", result.PageInfo.Page), zap.Int("nextPage", nextResult.PageInfo.Page))
result.PageInfo = nextResult.PageInfo
}
return &result, nil
}
// fetchRecordPage 获取单页记录
func fetchRecordPage[T any](wk *WK, rType RecordType, courseID, page string) (AllRecordResp[T], error) {
var result AllRecordResp[T]
resp, err := wk.newRequest().
SetQueryParams(map[string]string{
"courseId": courseID,
@@ -62,32 +87,13 @@ func GetRecords[T any](wk *WK, rType RecordType, courseID, page string) (*AllRec
}).
Get(fmt.Sprintf("https://%s/user/study_record%s.json", wk.Host, rType))
if err != nil {
return nil, err
return result, err
}
var result AllRecordResp[T]
if err := json.Unmarshal(resp.Bytes(), &result); err != nil {
log.Error("JSON解析失败", zap.Error(err))
return nil, err
return result, err
}
if !result.Status {
return &result, fmt.Errorf("接口报错: %s", result.Msg)
}
currentPage := result.PageInfo.Page
totalPages := result.PageInfo.PageCount
for currentPage < totalPages {
nextPage := fmt.Sprint(currentPage + 1)
nextResult, err := GetRecords[T](wk, rType, courseID, nextPage)
if err != nil {
return nil, err
}
result.List = append(result.List, nextResult.List...)
log.Debug("Page", zap.Int("currentPage", currentPage), zap.Int("Page", nextResult.PageInfo.Page))
currentPage = nextResult.PageInfo.Page
}
return &result, nil
return result, nil
}