代码质量优化

This commit is contained in:
ryan
2026-06-09 12:16:30 +08:00
parent f428839602
commit 4ac9857fe8
30 changed files with 199 additions and 149 deletions
@@ -81,11 +81,11 @@ func TestListAuthSources(t *testing.T) {
}
var resp util.ResponseAny
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
dataBytes, _ := json.Marshal(resp.Data)
var sources []model.AuthSource
json.Unmarshal(dataBytes, &sources)
_ = json.Unmarshal(dataBytes, &sources)
if len(sources) != 1 {
t.Errorf("expected 1 auth source, got %d", len(sources))
+5 -5
View File
@@ -103,7 +103,7 @@ func HandleLogWebSocket(c *gin.Context) {
if err != nil {
return
}
defer conn.Close()
defer func() { _ = conn.Close() }()
// 订阅 ring buffer
ch := logger.GlobalRingBuffer.Subscribe()
@@ -296,7 +296,7 @@ func GetAccessLogs(c *gin.Context) {
c.JSON(http.StatusInternalServerError, util.Err("查询 ClickHouse 日志明细失败: "+err.Error()))
return
}
defer rows.Close()
defer func() { _ = rows.Close() }()
var list []accessLogItem
var fetchUserIDs []uint64
@@ -424,7 +424,7 @@ func GetLogsAnalytics(c *gin.Context) {
}
if err == nil {
defer trendRows.Close()
defer func() { _ = trendRows.Close() }()
for trendRows.Next() {
var dt time.Time
var cnt uint64
@@ -454,7 +454,7 @@ func GetLogsAnalytics(c *gin.Context) {
browserCounts := make(map[string]uint64)
if err == nil {
defer uaRows.Close()
defer func() { _ = uaRows.Close() }()
for uaRows.Next() {
var ua string
var cnt uint64
@@ -493,7 +493,7 @@ func GetLogsAnalytics(c *gin.Context) {
userCountMap := make(map[uint64]uint64)
if err == nil {
defer userRows.Close()
defer func() { _ = userRows.Close() }()
for userRows.Next() {
var uid uint64
var cnt uint64
+1 -1
View File
@@ -206,7 +206,7 @@ func UpdateSystemConfig(c *gin.Context) {
updates := map[string]interface{}{
"description": req.Description,
}
if !(key == model.ConfigKeySMTPPassword && req.Value == "******") {
if key != model.ConfigKeySMTPPassword || req.Value != "******" {
updates["value"] = req.Value
config.Value = req.Value
}
@@ -140,11 +140,11 @@ func TestListSystemConfigs(t *testing.T) {
}
var resp util.ResponseAny
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
dataBytes, _ := json.Marshal(resp.Data)
var configs []model.SystemConfig
json.Unmarshal(dataBytes, &configs)
_ = json.Unmarshal(dataBytes, &configs)
// Defaults seed 23 configurations
if len(configs) != 23 {
@@ -158,11 +158,11 @@ func TestListSystemConfigs(t *testing.T) {
router.ServeHTTP(w, req)
var resp util.ResponseAny
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
dataBytes, _ := json.Marshal(resp.Data)
var configs []model.SystemConfig
json.Unmarshal(dataBytes, &configs)
_ = json.Unmarshal(dataBytes, &configs)
if len(configs) != 1 || configs[0].Key != model.ConfigKeyMaxAPIKeysPerUser {
t.Errorf("expected 1 business config (max_api_keys_per_user), got %d: %v", len(configs), configs)
@@ -187,11 +187,11 @@ func TestGetSystemConfig(t *testing.T) {
}
var resp util.ResponseAny
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
dataBytes, _ := json.Marshal(resp.Data)
var cfg model.SystemConfig
json.Unmarshal(dataBytes, &cfg)
_ = json.Unmarshal(dataBytes, &cfg)
if cfg.Value != "Wavelet" {
t.Errorf("expected 'Wavelet', got '%s'", cfg.Value)
@@ -240,7 +240,7 @@ func TestUpdateSystemConfig(t *testing.T) {
// Verify Redis
var redisConfig model.SystemConfig
db.HGetJSON(context.Background(), model.SystemConfigRedisHashKey, model.ConfigKeySiteName, &redisConfig)
_ = db.HGetJSON(context.Background(), model.SystemConfigRedisHashKey, model.ConfigKeySiteName, &redisConfig)
if redisConfig.Value != "Super Site Name" {
t.Errorf("redis cache value not updated, got '%s'", redisConfig.Value)
}
@@ -275,7 +275,7 @@ func TestTestSMTP(t *testing.T) {
if err != nil {
t.Fatalf("failed to start mock smtp server: %v", err)
}
defer l.Close()
defer func() { _ = l.Close() }()
port := l.Addr().(*net.TCPAddr).Port
@@ -284,40 +284,40 @@ func TestTestSMTP(t *testing.T) {
if err != nil {
return
}
defer conn.Close()
defer func() { _ = conn.Close() }()
writer := bufio.NewWriter(conn)
reader := bufio.NewReader(conn)
tp := textproto.NewReader(reader)
// 220 Ready
writer.WriteString("220 mock.smtp.com SMTP Ready\r\n")
writer.Flush()
_, _ = writer.WriteString("220 mock.smtp.com SMTP Ready\r\n")
_ = writer.Flush()
// Read HELO/EHLO
tp.ReadLine()
writer.WriteString("250-mock.smtp.com\r\n250 AUTH PLAIN\r\n")
writer.Flush()
_, _ = tp.ReadLine()
_, _ = writer.WriteString("250-mock.smtp.com\r\n250 AUTH PLAIN\r\n")
_ = writer.Flush()
// Read AUTH PLAIN
tp.ReadLine()
writer.WriteString("235 Authentication successful\r\n")
writer.Flush()
_, _ = tp.ReadLine()
_, _ = writer.WriteString("235 Authentication successful\r\n")
_ = writer.Flush()
// Read MAIL FROM
tp.ReadLine()
writer.WriteString("250 OK\r\n")
writer.Flush()
_, _ = tp.ReadLine()
_, _ = writer.WriteString("250 OK\r\n")
_ = writer.Flush()
// Read RCPT TO
tp.ReadLine()
writer.WriteString("250 OK\r\n")
writer.Flush()
_, _ = tp.ReadLine()
_, _ = writer.WriteString("250 OK\r\n")
_ = writer.Flush()
// Read DATA
tp.ReadLine()
writer.WriteString("354 Start mail input\r\n")
writer.Flush()
_, _ = tp.ReadLine()
_, _ = writer.WriteString("354 Start mail input\r\n")
_ = writer.Flush()
// Read body lines until dot
for {
@@ -326,13 +326,13 @@ func TestTestSMTP(t *testing.T) {
break
}
}
writer.WriteString("250 OK\r\n")
writer.Flush()
_, _ = writer.WriteString("250 OK\r\n")
_ = writer.Flush()
// Read QUIT
tp.ReadLine()
writer.WriteString("221 Bye\r\n")
writer.Flush()
_, _ = tp.ReadLine()
_, _ = writer.WriteString("221 Bye\r\n")
_ = writer.Flush()
}()
payload := TestSMTPRequest{
+4 -4
View File
@@ -45,7 +45,7 @@ func setupTaskTestEnvironment(t *testing.T) func() {
})
return func() {
if task.AsynqClient != nil {
task.AsynqClient.Close()
_ = task.AsynqClient.Close()
task.AsynqClient = nil
}
cleanup()
@@ -89,11 +89,11 @@ func TestListTaskTypes(t *testing.T) {
}
var resp util.ResponseAny
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
dataBytes, _ := json.Marshal(resp.Data)
var taskMetas []task.TaskMeta
json.Unmarshal(dataBytes, &taskMetas)
_ = json.Unmarshal(dataBytes, &taskMetas)
if len(taskMetas) == 0 {
t.Error("expected at least one dispatchable task type")
@@ -131,7 +131,7 @@ func TestDispatchTask(t *testing.T) {
assert.Equal(t, http.StatusOK, w.Code, "Body: %s", w.Body.String())
var resp util.ResponseAny
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
assert.Empty(t, resp.ErrorMsg)
assert.NotNil(t, resp.Data)
+2 -2
View File
@@ -136,11 +136,11 @@ func TestListTemplates(t *testing.T) {
}
var resp util.ResponseAny
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
dataBytes, _ := json.Marshal(resp.Data)
var templates []model.Template
json.Unmarshal(dataBytes, &templates)
_ = json.Unmarshal(dataBytes, &templates)
if len(templates) != 2 {
t.Errorf("expected 2 templates, got %d", len(templates))
+6 -6
View File
@@ -131,11 +131,11 @@ func TestListUsers(t *testing.T) {
router.ServeHTTP(w, req)
var resp util.ResponseAny
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
dataBytes, _ := json.Marshal(resp.Data)
var listResp listUsersResponse
json.Unmarshal(dataBytes, &listResp)
_ = json.Unmarshal(dataBytes, &listResp)
if len(listResp.Users) != 1 || listResp.Users[0].ID != 1001 {
t.Errorf("expected 1 user with ID 1001, got total %d", len(listResp.Users))
@@ -148,11 +148,11 @@ func TestListUsers(t *testing.T) {
router.ServeHTTP(w, req)
var resp util.ResponseAny
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
dataBytes, _ := json.Marshal(resp.Data)
var listResp listUsersResponse
json.Unmarshal(dataBytes, &listResp)
_ = json.Unmarshal(dataBytes, &listResp)
if len(listResp.Users) != 1 || listResp.Users[0].Username != "bob" {
t.Errorf("expected bob, got %v", listResp.Users)
@@ -226,7 +226,7 @@ func TestUpdateUserStatus(t *testing.T) {
}
var resp util.ResponseAny
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
if resp.ErrorMsg != cannotDisable {
t.Errorf("expected error message '%s', got '%s'", cannotDisable, resp.ErrorMsg)
}
@@ -326,7 +326,7 @@ func TestCreateUser(t *testing.T) {
}
var resp util.ResponseAny
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
if resp.ErrorMsg != usernameExists {
t.Errorf("expected error '%s', got '%s'", usernameExists, resp.ErrorMsg)
}
+3 -12
View File
@@ -214,15 +214,6 @@ func oidcDiscoveryResponse() *http.Response {
}
}
func jwksResponse() *http.Response {
jwksJSON, _ := json.Marshal(testJWKS)
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewReader(jwksJSON)),
Header: make(http.Header),
}
}
type mockClaims struct {
ID uint64 `json:"id"`
Issuer string `json:"iss"`
@@ -822,7 +813,7 @@ func TestCallbackBind(t *testing.T) {
router.GET("/test-helper/login-777", func(c *gin.Context) {
session := sessions.Default(c)
session.Set(UserIDKey, uint64(777))
session.Save()
_ = session.Save()
c.String(200, "ok")
})
@@ -874,7 +865,7 @@ func TestCallbackBind(t *testing.T) {
router.GET("/test-helper/login-888", func(c *gin.Context) {
session := sessions.Default(c)
session.Set(UserIDKey, uint64(888))
session.Save()
_ = session.Save()
c.String(200, "ok")
})
@@ -937,7 +928,7 @@ func TestExternalAccountsListAndDelete(t *testing.T) {
router.GET("/test-helper/login-555", func(c *gin.Context) {
session := sessions.Default(c)
session.Set(UserIDKey, uint64(555))
session.Save()
_ = session.Save()
c.String(200, "ok")
})
+1 -1
View File
@@ -82,7 +82,7 @@ func ServeFileByID(c *gin.Context) {
}
// Stream from CDN/S3
defer obj.Body.Close()
defer func() { _ = obj.Body.Close() }()
// Respond with the file content
c.DataFromReader(http.StatusOK, obj.ContentLength, obj.ContentType, obj.Body, nil)
+3 -3
View File
@@ -88,7 +88,7 @@ func UploadFile(c *gin.Context) {
c.JSON(http.StatusOK, util.Err(ErrOpenFileFailed))
return
}
defer file.Close()
defer func() { _ = file.Close() }()
// 校验大小
if header.Size > maxUploadSize {
@@ -318,7 +318,7 @@ func DownloadFile(c *gin.Context) {
return
}
defer obj.Body.Close()
defer func() { _ = obj.Body.Close() }()
_, _ = io.Copy(c.Writer, obj.Body)
}
@@ -372,7 +372,7 @@ func BatchDownloadFiles(c *gin.Context) {
// 开启实时 ZIP 压缩器并直接输出给 Response Writer
zipWriter := zip.NewWriter(c.Writer)
defer zipWriter.Close()
defer func() { _ = zipWriter.Close() }()
// 用于解决 ZIP 内部文件名称发生碰撞冲突的问题
usedNames := make(map[string]int)
+7 -7
View File
@@ -95,7 +95,7 @@ func createMultipartRequest(t *testing.T, fieldName, fileName string, fileConten
func TestUploadFile(t *testing.T) {
dbConn, _, cleanup := testhelper.SetupTestEnvironment(t)
defer cleanup()
defer os.RemoveAll("uploads") // Clean up local files created during tests
defer func() { _ = os.RemoveAll("uploads") }() // Clean up local files created during tests
authUser := &model.User{ID: 1001, Username: "test_user"}
router := setupTestRouter(authUser)
@@ -211,7 +211,7 @@ func TestUploadFile(t *testing.T) {
}
var resp testResponse
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
if resp.ErrorMsg == "" || !strings.Contains(resp.ErrorMsg, ErrUnsupportedFormat) {
t.Errorf("expected unsupported format error, got: %v", resp)
}
@@ -247,7 +247,7 @@ func TestUploadFile(t *testing.T) {
}
var resp2 testResponse
json.Unmarshal(w2.Body.Bytes(), &resp2)
_ = json.Unmarshal(w2.Body.Bytes(), &resp2)
if resp2.ErrorMsg != "" {
t.Fatalf("second upload was unsuccessful: %s", resp2.ErrorMsg)
@@ -304,7 +304,7 @@ func TestUploadFile(t *testing.T) {
}
var resp testResponse
json.Unmarshal(w.Body.Bytes(), &resp)
_ = json.Unmarshal(w.Body.Bytes(), &resp)
if resp.ErrorMsg != "" {
t.Fatalf("local upload failed: %s", resp.ErrorMsg)
@@ -334,7 +334,7 @@ func TestUploadFile(t *testing.T) {
func TestDownloadFile(t *testing.T) {
dbConn, _, cleanup := testhelper.SetupTestEnvironment(t)
defer cleanup()
defer os.RemoveAll("uploads")
defer func() { _ = os.RemoveAll("uploads") }()
authUser := &model.User{ID: 1001, Username: "test_user"}
router := setupTestRouter(authUser)
@@ -403,7 +403,7 @@ func TestDownloadFile(t *testing.T) {
func TestBatchDownloadFiles(t *testing.T) {
dbConn, _, cleanup := testhelper.SetupTestEnvironment(t)
defer cleanup()
defer os.RemoveAll("uploads")
defer func() { _ = os.RemoveAll("uploads") }()
authUser := &model.User{ID: 1001, Username: "test_user"}
router := setupTestRouter(authUser)
@@ -495,7 +495,7 @@ func TestBatchDownloadFiles(t *testing.T) {
t.Fatalf("failed to open zip file entry %s: %v", f.Name, err)
}
content, _ := io.ReadAll(rc)
rc.Close()
_ = rc.Close()
extracted[f.Name] = string(content)
}
+4 -3
View File
@@ -18,6 +18,7 @@ limitations under the License.
package upload
import (
"errors"
"fmt"
"strings"
)
@@ -27,7 +28,7 @@ const maxS3KeyLength = 1024
// ValidateS3Key validates an S3 object key for safety.
func ValidateS3Key(key string) error {
if key == "" {
return fmt.Errorf(ErrS3KeyRequired)
return errors.New(ErrS3KeyRequired)
}
if len(key) > maxS3KeyLength {
@@ -35,11 +36,11 @@ func ValidateS3Key(key string) error {
}
if strings.HasPrefix(key, "/") {
return fmt.Errorf(ErrS3KeyStartsWithSlash)
return errors.New(ErrS3KeyStartsWithSlash)
}
if strings.Contains(key, "\x00") {
return fmt.Errorf(ErrS3KeyContainsNullBytes)
return errors.New(ErrS3KeyContainsNullBytes)
}
return nil
+2 -2
View File
@@ -125,7 +125,7 @@ func sendEmailVerificationCode(ctx context.Context, email, scene, templateName s
// 存验证码,5分钟有效
if err := db.SetJSON(ctx, codeKey, code, 5*time.Minute); err != nil {
return fmt.Errorf(errGenerateEmailCodeFailed)
return errors.New(errGenerateEmailCodeFailed)
}
// 存冷却,60秒有效
_ = db.SetJSON(ctx, cooldownKey, "1", 60*time.Second)
@@ -139,7 +139,7 @@ func sendEmailVerificationCode(ctx context.Context, email, scene, templateName s
payloadBytes, _ := json.Marshal(payload)
_, err = task.DispatchTask(ctx, task.TaskTypeSendEmail, payloadBytes, "system")
if err != nil {
return fmt.Errorf(errDispatchEmailTaskFailed)
return errors.New(errDispatchEmailTaskFailed)
}
return nil
}