ProxySwitcher/util/config.go

62 lines
1.0 KiB
Go
Raw Permalink Normal View History

2024-08-30 16:08:24 +00:00
package util
import (
"encoding/json"
"fmt"
"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 {
name := info.Name()
isExample := strings.HasSuffix(name, ".example.json")
notJson := !strings.HasSuffix(name, ".json")
if info.IsDir() || isExample || notJson {
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(cfgPath string, config Config) error {
data, err := json.Marshal(config)
if err != nil {
return err
}
cfgName := fmt.Sprintf("%s.json", config.Name)
cfgFile := filepath.Join(cfgPath, cfgName)
err = os.WriteFile(cfgFile, data, 0666)
return err
}