V2bX/conf/conf.go

91 lines
2.1 KiB
Go
Raw Normal View History

package conf
2022-09-12 23:08:20 -04:00
import (
"fmt"
2022-10-09 23:31:15 -04:00
"github.com/fsnotify/fsnotify"
2022-09-12 23:08:20 -04:00
"gopkg.in/yaml.v3"
2023-06-01 21:19:37 -04:00
"io"
2022-10-09 23:31:15 -04:00
"log"
2022-09-12 23:08:20 -04:00
"os"
"path"
)
type Conf struct {
2023-05-18 21:49:31 -04:00
LogConfig *LogConfig `yaml:"Log"`
DnsConfigPath string `yaml:"DnsConfigPath"`
InboundConfigPath string `yaml:"InboundConfigPath"`
OutboundConfigPath string `yaml:"OutboundConfigPath"`
RouteConfigPath string `yaml:"RouteConfigPath"`
ConnectionConfig *ConnectionConfig `yaml:"ConnectionConfig"`
NodesConfig []*NodeConfig `yaml:"Nodes"`
}
func New() *Conf {
return &Conf{
LogConfig: NewLogConfig(),
DnsConfigPath: "",
InboundConfigPath: "",
OutboundConfigPath: "",
RouteConfigPath: "",
2023-05-18 21:49:31 -04:00
ConnectionConfig: NewConnectionConfig(),
NodesConfig: []*NodeConfig{},
}
}
2022-09-12 23:08:20 -04:00
func (p *Conf) LoadFromPath(filePath string) error {
confPath := path.Dir(filePath)
os.Setenv("XRAY_LOCATION_ASSET", confPath)
os.Setenv("XRAY_LOCATION_CONFIG", confPath)
f, err := os.Open(filePath)
if err != nil {
2022-10-09 23:31:15 -04:00
return fmt.Errorf("open config file error: %s", err)
2022-09-12 23:08:20 -04:00
}
2023-06-01 21:19:37 -04:00
defer f.Close()
content, err := io.ReadAll(f)
if err != nil {
return fmt.Errorf("read file error: %s", err)
}
err = yaml.Unmarshal(content, p)
2022-09-12 23:08:20 -04:00
if err != nil {
2022-10-09 23:31:15 -04:00
return fmt.Errorf("decode config error: %s", err)
}
2023-06-01 21:19:37 -04:00
old := &OldConfig{}
err = yaml.Unmarshal(content, old)
if err == nil {
migrateOldConfig(p, old)
}
2022-10-09 23:31:15 -04:00
return nil
}
func (p *Conf) Watch(filePath string, reload func()) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return fmt.Errorf("new watcher error: %s", err)
}
go func() {
defer watcher.Close()
for {
select {
2023-05-18 21:49:31 -04:00
case <-watcher.Events:
log.Println("config dir changed, reloading...")
*p = *New()
err := p.LoadFromPath(filePath)
if err != nil {
log.Printf("reload config error: %s", err)
2022-10-09 23:31:15 -04:00
}
2023-05-18 21:49:31 -04:00
reload()
log.Println("reload config success")
2022-10-09 23:31:15 -04:00
case err := <-watcher.Errors:
if err != nil {
log.Printf("File watcher error: %s", err)
2022-10-09 23:31:15 -04:00
}
}
}
}()
err = watcher.Add(path.Dir(filePath))
if err != nil {
return fmt.Errorf("watch file error: %s", err)
2022-09-12 23:08:20 -04:00
}
return nil
}