Skip to content

Commit 94448f8

Browse files
committed
test: fix golangci-lint
1 parent bb6fd64 commit 94448f8

29 files changed

Lines changed: 176 additions & 196 deletions

internal/flags/config.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,7 @@ func ParseConfig() AppFlags {
9292

9393
// Multi-value flags
9494
rules.RLockHooksFiles()
95-
var hooksFiles hook.HooksFiles
96-
hooksFiles = make(hook.HooksFiles, len(rules.HooksFiles))
95+
hooksFiles := make(hook.HooksFiles, len(rules.HooksFiles))
9796
copy(hooksFiles, rules.HooksFiles)
9897
rules.RUnlockHooksFiles()
9998
fs.Var(&hooksFiles, "hooks", "path to the json file containing defined hooks the webhook should serve, use multiple times to load from different files")

internal/flags/config_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,9 @@ func TestParseConfig_HooksFromEnv(t *testing.T) {
6363
os.Args = oldArgs
6464
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
6565
if oldHooks != "" {
66-
os.Setenv(ENV_KEY_HOOKS, oldHooks)
66+
_ = os.Setenv(ENV_KEY_HOOKS, oldHooks)
6767
} else {
68-
os.Unsetenv(ENV_KEY_HOOKS)
68+
_ = os.Unsetenv(ENV_KEY_HOOKS)
6969
}
7070
rules.LockHooksFiles()
7171
rules.HooksFiles = nil
@@ -77,7 +77,7 @@ func TestParseConfig_HooksFromEnv(t *testing.T) {
7777
rules.HooksFiles = nil
7878
rules.UnlockHooksFiles()
7979

80-
os.Setenv(ENV_KEY_HOOKS, "env_hooks1.json,env_hooks2.json")
80+
_ = os.Setenv(ENV_KEY_HOOKS, "env_hooks1.json,env_hooks2.json")
8181
os.Args = []string{"webhook"}
8282

8383
result := ParseConfig()

internal/flags/flags_test.go

Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,15 @@ func TestParseConfig_DefaultValues(t *testing.T) {
2424
if val := os.Getenv(key); val != "" {
2525
originalEnv[key] = val
2626
}
27-
os.Unsetenv(key)
27+
_ = os.Unsetenv(key)
2828
}
2929

3030
originalArgs := os.Args
3131
defer func() {
3232
os.Args = originalArgs
3333
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
3434
for key := range originalEnv {
35-
os.Setenv(key, originalEnv[key])
35+
_ = os.Setenv(key, originalEnv[key])
3636
}
3737
}()
3838

@@ -83,33 +83,33 @@ func TestParseConfig_FromEnvVars(t *testing.T) {
8383
os.Args = originalArgs
8484
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
8585
for key := range originalEnv {
86-
os.Setenv(key, originalEnv[key])
86+
_ = os.Setenv(key, originalEnv[key])
8787
}
8888
for _, key := range envKeys {
8989
if _, exists := originalEnv[key]; !exists {
90-
os.Unsetenv(key)
90+
_ = os.Unsetenv(key)
9191
}
9292
}
9393
}()
9494

9595
// Set custom environment variables
96-
os.Setenv(ENV_KEY_HOST, "127.0.0.1")
97-
os.Setenv(ENV_KEY_PORT, "8080")
98-
os.Setenv(ENV_KEY_VERBOSE, "true")
99-
os.Setenv(ENV_KEY_DEBUG, "true")
100-
os.Setenv(ENV_KEY_NO_PANIC, "true")
101-
os.Setenv(ENV_KEY_HOT_RELOAD, "true")
102-
os.Setenv(ENV_KEY_LOG_PATH, "/tmp/test.log")
103-
os.Setenv(ENV_KEY_HOOKS_URLPREFIX, "webhooks")
104-
os.Setenv(ENV_KEY_TEMPLATE, "true")
105-
os.Setenv(ENV_KEY_X_REQUEST_ID, "true")
106-
os.Setenv(ENV_KEY_MAX_MPART_MEM, "2097152")
107-
os.Setenv(ENV_KEY_GID, "1000")
108-
os.Setenv(ENV_KEY_UID, "1000")
109-
os.Setenv(ENV_KEY_HTTP_METHODS, "POST,GET")
110-
os.Setenv(ENV_KEY_PID_FILE, "/tmp/webhook.pid")
111-
os.Setenv(ENV_KEY_LANG, "zh-CN")
112-
os.Setenv(ENV_KEY_I18N, "/tmp/locales")
96+
_ = os.Setenv(ENV_KEY_HOST, "127.0.0.1")
97+
_ = os.Setenv(ENV_KEY_PORT, "8080")
98+
_ = os.Setenv(ENV_KEY_VERBOSE, "true")
99+
_ = os.Setenv(ENV_KEY_DEBUG, "true")
100+
_ = os.Setenv(ENV_KEY_NO_PANIC, "true")
101+
_ = os.Setenv(ENV_KEY_HOT_RELOAD, "true")
102+
_ = os.Setenv(ENV_KEY_LOG_PATH, "/tmp/test.log")
103+
_ = os.Setenv(ENV_KEY_HOOKS_URLPREFIX, "webhooks")
104+
_ = os.Setenv(ENV_KEY_TEMPLATE, "true")
105+
_ = os.Setenv(ENV_KEY_X_REQUEST_ID, "true")
106+
_ = os.Setenv(ENV_KEY_MAX_MPART_MEM, "2097152")
107+
_ = os.Setenv(ENV_KEY_GID, "1000")
108+
_ = os.Setenv(ENV_KEY_UID, "1000")
109+
_ = os.Setenv(ENV_KEY_HTTP_METHODS, "POST,GET")
110+
_ = os.Setenv(ENV_KEY_PID_FILE, "/tmp/webhook.pid")
111+
_ = os.Setenv(ENV_KEY_LANG, "zh-CN")
112+
_ = os.Setenv(ENV_KEY_I18N, "/tmp/locales")
113113

114114
os.Args = []string{"webhook"}
115115

@@ -159,20 +159,20 @@ func TestParseConfig_CLIPriorityOverEnv(t *testing.T) {
159159
os.Args = originalArgs
160160
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
161161
if originalHost != "" {
162-
os.Setenv(ENV_KEY_HOST, originalHost)
162+
_ = os.Setenv(ENV_KEY_HOST, originalHost)
163163
} else {
164-
os.Unsetenv(ENV_KEY_HOST)
164+
_ = os.Unsetenv(ENV_KEY_HOST)
165165
}
166166
if originalPort != "" {
167-
os.Setenv(ENV_KEY_PORT, originalPort)
167+
_ = os.Setenv(ENV_KEY_PORT, originalPort)
168168
} else {
169-
os.Unsetenv(ENV_KEY_PORT)
169+
_ = os.Unsetenv(ENV_KEY_PORT)
170170
}
171171
}()
172172

173173
// Set environment variables
174-
os.Setenv(ENV_KEY_HOST, "10.0.0.1")
175-
os.Setenv(ENV_KEY_PORT, "3000")
174+
_ = os.Setenv(ENV_KEY_HOST, "10.0.0.1")
175+
_ = os.Setenv(ENV_KEY_PORT, "3000")
176176

177177
// CLI should override ENV
178178
os.Args = []string{"webhook", "-ip", "192.168.1.1", "-port", "9000"}

internal/flags/validate_test.go

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,23 @@ func TestValidate_Port(t *testing.T) {
103103
func TestValidate_LogPath(t *testing.T) {
104104
tempDir := t.TempDir()
105105

106+
// Create a temporary hooks file to avoid validation errors from validateHookFiles
107+
hookFile := filepath.Join(tempDir, "hooks.json")
108+
hookContent := `[]`
109+
err := os.WriteFile(hookFile, []byte(hookContent), 0644)
110+
require.NoError(t, err)
111+
112+
// Setup rules so that Validate does not fail on missing hooks.json
113+
rules.LockHooksFiles()
114+
oldHooksFiles := rules.HooksFiles
115+
rules.HooksFiles = []string{hookFile}
116+
rules.UnlockHooksFiles()
117+
defer func() {
118+
rules.LockHooksFiles()
119+
rules.HooksFiles = oldHooksFiles
120+
rules.UnlockHooksFiles()
121+
}()
122+
106123
tests := []struct {
107124
name string
108125
logPath string
@@ -155,12 +172,13 @@ func TestValidate_LogPath(t *testing.T) {
155172

156173
flags := createValidFlags()
157174
flags.LogPath = tt.logPath
175+
flags.HooksFiles = []string{hookFile}
158176
result := Validate(flags)
159177
if tt.hasError {
160178
assert.True(t, result.HasErrors())
161179
} else if tt.logPath != "" {
162-
// Only check if log path is provided
163-
// Empty log path is valid and won't trigger validation
180+
// Only check if log path is provided; empty log path is valid and won't trigger validation
181+
assert.False(t, result.HasErrors())
164182
}
165183
})
166184
}

internal/fn/io_test.go

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@ func TestScanDirByExt(t *testing.T) {
1515
testFile2 := filepath.Join(tempDir, "test2.jpg")
1616
testFile3 := filepath.Join(tempDir, "test3.txt")
1717

18-
os.Create(testFile1)
19-
os.Create(testFile2)
20-
os.Create(testFile3)
18+
_, _ = os.Create(testFile1)
19+
_, _ = os.Create(testFile2)
20+
_, _ = os.Create(testFile3)
2121

22-
defer os.Remove(testFile1)
23-
defer os.Remove(testFile2)
24-
defer os.Remove(testFile3)
22+
defer func() { _ = os.Remove(testFile1) }()
23+
defer func() { _ = os.Remove(testFile2) }()
24+
defer func() { _ = os.Remove(testFile3) }()
2525

2626
txtFiles := fn.ScanDirByExt(tempDir, ".txt")
2727
assert.Equal(t, []string{testFile1, testFile3}, txtFiles)
@@ -43,10 +43,10 @@ func TestScanDirByExt(t *testing.T) {
4343

4444
// Test with nested directories
4545
subDir := filepath.Join(tempDir, "subdir")
46-
os.Mkdir(subDir, 0755)
46+
_ = os.Mkdir(subDir, 0755)
4747
testFile4 := filepath.Join(subDir, "test4.txt")
48-
os.Create(testFile4)
49-
defer os.Remove(testFile4)
48+
_, _ = os.Create(testFile4)
49+
defer func() { _ = os.Remove(testFile4) }()
5050

5151
txtFiles4 := fn.ScanDirByExt(tempDir, ".txt")
5252
assert.Contains(t, txtFiles4, testFile4)
@@ -70,13 +70,13 @@ func TestScanDirByExt_CaseInsensitive(t *testing.T) {
7070
testFile2 := filepath.Join(tempDir, "test2.txt")
7171
testFile3 := filepath.Join(tempDir, "test3.Txt")
7272

73-
os.Create(testFile1)
74-
os.Create(testFile2)
75-
os.Create(testFile3)
73+
_, _ = os.Create(testFile1)
74+
_, _ = os.Create(testFile2)
75+
_, _ = os.Create(testFile3)
7676

77-
defer os.Remove(testFile1)
78-
defer os.Remove(testFile2)
79-
defer os.Remove(testFile3)
77+
defer func() { _ = os.Remove(testFile1) }()
78+
defer func() { _ = os.Remove(testFile2) }()
79+
defer func() { _ = os.Remove(testFile3) }()
8080

8181
txtFiles := fn.ScanDirByExt(tempDir, ".txt")
8282
assert.Len(t, txtFiles, 3)

internal/hook/hook_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -516,7 +516,7 @@ var hooksLoadFromFileTests = []struct {
516516

517517
func TestHooksLoadFromFile(t *testing.T) {
518518
secret := `foo"123`
519-
os.Setenv("XXXTEST_SECRET", secret)
519+
_ = os.Setenv("XXXTEST_SECRET", secret)
520520

521521
for _, tt := range hooksLoadFromFileTests {
522522
h := &Hooks{}
@@ -529,7 +529,7 @@ func TestHooksLoadFromFile(t *testing.T) {
529529

530530
func TestHooksTemplateLoadFromFile(t *testing.T) {
531531
secret := `foo"123`
532-
os.Setenv("XXXTEST_SECRET", secret)
532+
_ = os.Setenv("XXXTEST_SECRET", secret)
533533

534534
for _, tt := range hooksLoadFromFileTests {
535535
if !tt.asTemplate {

internal/middleware/dumper.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ func DumperWithConfig(w io.Writer, config DumperConfig) func(http.Handler) http.
5252
// Dump request (包含请求体)
5353
bd, err := httputil.DumpRequest(r, true)
5454
if err != nil {
55-
buf.WriteString(fmt.Sprintf("[%s] Error dumping request for debugging: %s\n", rid, err))
55+
fmt.Fprintf(buf, "[%s] Error dumping request for debugging: %s\n", rid, err)
5656
} else {
5757
// 脱敏请求转储
5858
sanitized := SanitizeDumpRequest(bd, config.IncludeRequestBody)
@@ -66,13 +66,13 @@ func DumperWithConfig(w io.Writer, config DumperConfig) func(http.Handler) http.
6666
// 找到空行,停止处理(空行后是请求体)
6767
break
6868
}
69-
buf.WriteString(fmt.Sprintf("> [%s] ", rid))
69+
fmt.Fprintf(buf, "> [%s] ", rid)
7070
buf.WriteString(line + "\n")
7171
}
7272

7373
// 如果不包含请求体,添加提示
7474
if !config.IncludeRequestBody && len(bd) > 0 {
75-
buf.WriteString(fmt.Sprintf("> [%s] [Request body omitted for security - use --log-request-body to include]\n", rid))
75+
fmt.Fprintf(buf, "> [%s] [Request body omitted for security - use --log-request-body to include]\n", rid)
7676
}
7777
}
7878

@@ -88,7 +88,7 @@ func DumperWithConfig(w io.Writer, config DumperConfig) func(http.Handler) http.
8888
h.ServeHTTP(dupper, r)
8989

9090
// Response Status
91-
buf.WriteString(fmt.Sprintf("< [%s] %d %s\n", rid, dupper.Status, http.StatusText(dupper.Status)))
91+
fmt.Fprintf(buf, "< [%s] %d %s\n", rid, dupper.Status, http.StatusText(dupper.Status))
9292

9393
// Response Headers
9494
keys := make([]string, len(dupper.Header()))
@@ -99,7 +99,7 @@ func DumperWithConfig(w io.Writer, config DumperConfig) func(http.Handler) http.
9999
}
100100
sort.Strings(keys)
101101
for _, k := range keys {
102-
buf.WriteString(fmt.Sprintf("< [%s] %s: %s\n", rid, k, strings.Join(dupper.Header()[k], ", ")))
102+
fmt.Fprintf(buf, "< [%s] %s: %s\n", rid, k, strings.Join(dupper.Header()[k], ", "))
103103
}
104104

105105
// Response Body (脱敏处理)
@@ -111,15 +111,15 @@ func DumperWithConfig(w io.Writer, config DumperConfig) func(http.Handler) http.
111111
sanitizedBody := SanitizeRequestBody(responseContentType, responseBody, config.IncludeRequestBody)
112112

113113
if sanitizedBody != "" {
114-
buf.WriteString(fmt.Sprintf("< [%s]\n", rid))
114+
fmt.Fprintf(buf, "< [%s]\n", rid)
115115
sc := bufio.NewScanner(bytes.NewBufferString(sanitizedBody))
116116
sc.Split(bufio.ScanLines)
117117
for sc.Scan() {
118-
buf.WriteString(fmt.Sprintf("< [%s] ", rid))
118+
fmt.Fprintf(buf, "< [%s] ", rid)
119119
buf.WriteString(sc.Text() + "\n")
120120
}
121121
} else if !config.IncludeRequestBody {
122-
buf.WriteString(fmt.Sprintf("< [%s] [Response body omitted for security]\n", rid))
122+
fmt.Fprintf(buf, "< [%s] [Response body omitted for security]\n", rid)
123123
}
124124
}
125125
_, err = w.Write(buf.Bytes())

internal/middleware/dumper_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ func TestDumper(t *testing.T) {
1717
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1818
w.Header().Set("Content-Type", "application/json")
1919
w.WriteHeader(http.StatusOK)
20-
w.Write([]byte(`{"status":"ok"}`))
20+
_, _ = w.Write([]byte(`{"status":"ok"}`))
2121
}),
2222
)
2323

@@ -88,7 +88,7 @@ func TestDumperWithConfig(t *testing.T) {
8888
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
8989
w.Header().Set("Content-Type", "application/json")
9090
w.WriteHeader(http.StatusOK)
91-
w.Write([]byte(`{"status":"ok"}`))
91+
_, _ = w.Write([]byte(`{"status":"ok"}`))
9292
}),
9393
)
9494

@@ -111,7 +111,7 @@ func TestDumperWithConfig_IncludeRequestBody(t *testing.T) {
111111
})(
112112
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
113113
w.WriteHeader(http.StatusOK)
114-
w.Write([]byte("response body"))
114+
_, _ = w.Write([]byte("response body"))
115115
}),
116116
)
117117

@@ -134,7 +134,7 @@ func TestDumperWithConfig_ExcludeRequestBody(t *testing.T) {
134134
})(
135135
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
136136
w.WriteHeader(http.StatusOK)
137-
w.Write([]byte("response body"))
137+
_, _ = w.Write([]byte("response body"))
138138
}),
139139
)
140140

@@ -181,6 +181,6 @@ func TestResponseDupper_Flush(t *testing.T) {
181181

182182
// Test that Flush doesn't panic (if ResponseWriter implements Flusher)
183183
// httptest.NewRecorder doesn't implement Flusher, so this should be safe
184-
dupper.Write([]byte("test"))
184+
_, _ = dupper.Write([]byte("test"))
185185
assert.Equal(t, []byte("test"), w.Body.Bytes())
186186
}

internal/middleware/logger.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import (
1111
func NewLogger() func(next http.Handler) http.Handler {
1212
if logger.DefaultLogger == nil {
1313
// 如果 logger 未初始化,使用默认配置
14-
logger.Init(true, false, "", false)
14+
_ = logger.Init(true, false, "", false)
1515
}
1616

1717
cfg := loggerkit.DefaultMiddlewareConfig()

internal/middleware/logger_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func TestNewLogger(t *testing.T) {
1616
// Create a test handler
1717
handler := logger(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1818
w.WriteHeader(http.StatusOK)
19-
w.Write([]byte("OK"))
19+
_, _ = w.Write([]byte("OK"))
2020
}))
2121

2222
// Create a test request

0 commit comments

Comments
 (0)