ProxySwitcher/util/config.go

59 lines
925 B
Go
Raw Normal View History

2024-08-30 16:08:24 +00:00
package util
import (
"encoding/json"
"io/fs"
"path/filepath"
2024-09-24 12:49:47 +00:00
"strings"
2024-08-30 16:08:24 +00:00
"io"
"os"
)
func ReadConfigs(cfgPath string) ([]*Config, error) {
var configs []*Config
2024-08-30 16:08:24 +00:00
err := filepath.Walk(cfgPath, func(path string, info fs.FileInfo, err error) error {
2024-09-24 12:49:47 +00:00
if info.IsDir() || strings.HasSuffix(info.Name(), ".example.json") {
return nil
}
2024-08-30 16:08:24 +00:00
file, err := os.Open(path)
2024-08-30 16:08:24 +00:00
if err != nil {
return nil
}
defer file.Close()
2024-08-30 16:08:24 +00:00
bytes, err := io.ReadAll(file)
if err != nil {
return nil
}
var config *Config
err = json.Unmarshal(bytes, &config)
if err != nil {
return nil
}
configs = append(configs, config)
return nil
})
return configs, err
2024-08-30 16:08:24 +00:00
}
func SaveConfig(name string, config Config) error {
configs, _ := ReadConfigs(name)
configs = append(configs, &config)
data, err := json.Marshal(configs)
if err != nil {
return err
}
err = os.WriteFile(name, data, 0666)
return err
}