Skip to content

Commit ac62081

Browse files
committed
feat(mipush): handle missing key by environment mode
Refactor `getMipushKey()` to behave differently across environments: - In production: fatal on missing key. - In dev/test: warn and continue with empty key. - In perf: use mock key. - Default: fatal for unknown mode. This prevents non-production environments from crashing when the Mipush key is not present, while preserving strict validation in production.
1 parent 946b338 commit ac62081

1 file changed

Lines changed: 42 additions & 4 deletions

File tree

push/mipush/init.go

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,53 @@ var client = http.Client{Timeout: timeout}
1717
var authorization string
1818

1919
func init() {
20+
2021
log.Debug().Msg("init mipush")
21-
authorization = "key=" + getMipushKey()
22+
key, _ := getMipushKey()
23+
authorization = "key=" + key
2224
}
2325

24-
func getMipushKey() string {
26+
func getMipushKey() (string, error) {
2527
data, err := os.ReadFile(config.Config.MipushKeyPath)
28+
2629
if err != nil {
2730
pwd, _ := os.Getwd()
28-
log.Fatal().Str("pwd", pwd).Err(err).Str("scope", "init mipush").Msg("failed to read mipush key")
31+
32+
switch config.Config.Mode {
33+
case "production":
34+
// 在生产环境中严格要求 key 存在
35+
log.Fatal().
36+
Str("pwd", pwd).
37+
Err(err).
38+
Str("scope", "init mipush").
39+
Msg("failed to read mipush key in production")
40+
// 不会执行到这里
41+
return "", err
42+
43+
case "dev", "test":
44+
// 在开发或测试环境中只警告,不终止
45+
log.Warn().
46+
Str("pwd", pwd).
47+
Err(err).
48+
Str("scope", "init mipush").
49+
Msg("failed to read mipush key, using empty key in non-production mode")
50+
return "", nil
51+
52+
case "perf":
53+
// 压测环境用 mock key
54+
log.Info().
55+
Str("scope", "init mipush").
56+
Msg("using mock mipush key for perf mode")
57+
return "mock-mipush-key", nil
58+
59+
default:
60+
// 未知模式时明确报错退出
61+
log.Fatal().
62+
Str("scope", "init mipush").
63+
Str("mode", config.Config.Mode).
64+
Msg("unknown mode while reading mipush key")
65+
return "", err
66+
}
2967
}
30-
return string(data)
68+
return string(data), nil
3169
}

0 commit comments

Comments
 (0)