Files
flvx/go-gost/x/config/persist.go
T
sagit 3f374df724 fix: 保留用户/规则高级设置并增强节点运行时恢复 (#468)
* fix: 用户编辑时 maxConn 字段未正确回填

- User 接口添加 maxConn 类型定义
- handleEdit 中回填 maxConn 值
- normalizeUserItem 添加 maxConn 字段处理

解决编辑用户时最大连接数显示为 0 的问题

* fix: 保留转发设置并增强节点运行时恢复
2026-04-25 18:12:13 +08:00

95 lines
2.0 KiB
Go

package config
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
)
var (
persistPath string
persistMu sync.Mutex
persistEnable bool
)
// SetPersistPath sets the file path where runtime config changes will be
// automatically persisted. Call this once during agent startup before any
// OnUpdate mutations occur.
func SetPersistPath(path string) {
persistMu.Lock()
defer persistMu.Unlock()
persistPath = path
}
func PersistPath() string {
persistMu.Lock()
defer persistMu.Unlock()
return persistPath
}
// EnablePersist turns on automatic persistence. Call this after the initial
// config has been loaded (e.g. after program.Start) so that startup loading
// does not trigger redundant disk writes.
func EnablePersist() {
persistMu.Lock()
defer persistMu.Unlock()
persistEnable = true
}
// persist writes the current global config to the configured file atomically.
func persist() {
persistMu.Lock()
path := persistPath
enabled := persistEnable
persistMu.Unlock()
if !enabled || path == "" {
return
}
cfg := Global()
if cfg == nil {
return
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetIndent("", " ")
if err := enc.Encode(cfg); err != nil {
fmt.Printf("⚠️ config persist: marshal failed: %v\n", err)
return
}
// Atomic write: write to temp file then rename
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".gost-*.tmp")
if err != nil {
fmt.Printf("⚠️ config persist: create temp file failed: %v\n", err)
return
}
tmpName := tmp.Name()
if _, err := tmp.Write(buf.Bytes()); err != nil {
tmp.Close()
os.Remove(tmpName)
fmt.Printf("⚠️ config persist: write failed: %v\n", err)
return
}
if err := tmp.Close(); err != nil {
os.Remove(tmpName)
fmt.Printf("⚠️ config persist: close temp file failed: %v\n", err)
return
}
if err := os.Rename(tmpName, path); err != nil {
os.Remove(tmpName)
fmt.Printf("⚠️ config persist: rename failed: %v\n", err)
return
}
fmt.Printf("💾 节点配置已持久化到 %s\n", path)
}