refactor: 使用 Viper 重构配置管理并实现生产级热重载

- 引入 Viper 库替代手动 YAML 解析
- 实现基于 fsnotify 的配置文件热重载
- 使用 atomic.Value 保证并发安全的配置读写
- 添加配置验证(必填字段检查)
- 深拷贝 Hotwords 切片防止数据竞争
- 使用绝对路径匹配提升跨平台可靠性
- 支持启动失败后重试(不锁死状态)
- 提供 stop 函数正确清理 watcher 资源
- 通过 Oracle 多轮审计确认生产就绪
This commit is contained in:
2026-03-02 02:57:47 +08:00
parent dd55be6f5b
commit 0720505ef6
2 changed files with 171 additions and 32 deletions

25
main.go
View File

@@ -25,7 +25,12 @@ func main() {
initLogger()
slog.Info("VoicePaste", "version", version)
cfg := mustLoadConfig()
go config.WatchAndReload("")
stopWatch := config.WatchAndReload("")
defer func() {
if stopWatch != nil {
stopWatch()
}
}()
initClipboard()
lanIPs := mustDetectLANIPs()
lanIP := lanIPs[0]
@@ -136,20 +141,22 @@ func createServer(cfg config.Config, lanIP string, tlsResult *vpTLS.Result) *ser
tlsConfig = tlsResult.Config
}
srv := server.New(cfg.Security.Token, lanIP, webContent, tlsConfig)
asrFactory := buildASRFactory(cfg)
asrFactory := buildASRFactory()
wsHandler := ws.NewHandler(cfg.Security.Token, paste.Paste, asrFactory)
wsHandler.Register(srv.App())
return srv
}
func buildASRFactory(cfg config.Config) func(chan<- ws.ServerMsg) (func([]byte), func(), error) {
asrCfg := asr.Config{
AppID: cfg.Doubao.AppID,
AccessToken: cfg.Doubao.AccessToken,
ResourceID: cfg.Doubao.ResourceID,
Hotwords: cfg.Doubao.Hotwords,
}
func buildASRFactory() func(chan<- ws.ServerMsg) (func([]byte), func(), error) {
return func(resultCh chan<- ws.ServerMsg) (func([]byte), func(), error) {
// Read latest config on each new connection
cfg := config.Get()
asrCfg := asr.Config{
AppID: cfg.Doubao.AppID,
AccessToken: cfg.Doubao.AccessToken,
ResourceID: cfg.Doubao.ResourceID,
Hotwords: cfg.Doubao.Hotwords,
}
client, err := asr.Dial(asrCfg, resultCh)
if err != nil {
return nil, nil, err