From f13b310d522717d1691c679ac34790c1e4df8f62 Mon Sep 17 00:00:00 2001 From: Dnomd343 Date: Mon, 17 Oct 2022 19:51:49 +0800 Subject: [PATCH] feat: default config with json or toml format --- cmd/config/default.go | 44 +++++++++++++++++++++++++++++++++++++++++-- cmd/config/main.go | 3 +-- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/cmd/config/default.go b/cmd/config/default.go index b24a358..6a6cb97 100644 --- a/cmd/config/default.go +++ b/cmd/config/default.go @@ -1,5 +1,15 @@ package config +import ( + "XProxy/cmd/common" + "bytes" + "encoding/json" + "github.com/BurntSushi/toml" + log "github.com/sirupsen/logrus" + "gopkg.in/yaml.v3" + "path" +) + var defaultConfig = `# default configure file for xproxy proxy: core: xray @@ -17,6 +27,36 @@ asset: update: cron: "0 5 6 * * *" url: - geoip.dat: "https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat" - geosite.dat: "https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat" + geoip.dat: https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat + geosite.dat: https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat ` + +func toJSON(yamlConfig string) string { // YAML -> JSON + var config interface{} + if err := yaml.Unmarshal([]byte(yamlConfig), &config); err != nil { + log.Panicf("Default config error -> %v", err) + } + jsonRaw, _ := json.Marshal(config) + return string(jsonRaw) +} + +func toTOML(yamlConfig string) string { // YAML -> TOML + var config interface{} + if err := yaml.Unmarshal([]byte(yamlConfig), &config); err != nil { + log.Panicf("Default config error -> %v", err) + } + buf := new(bytes.Buffer) + _ = toml.NewEncoder(buf).Encode(config) + return buf.String() +} + +func loadDefaultConfig(configFile string) { + log.Infof("Load default configure -> %s", configFile) + suffix := path.Ext(configFile) + if suffix == ".json" { + defaultConfig = toJSON(defaultConfig) + } else if suffix == ".toml" { + defaultConfig = toTOML(defaultConfig) + } + common.WriteFile(configFile, defaultConfig, false) +} diff --git a/cmd/config/main.go b/cmd/config/main.go index f670a37..ffa9bda 100644 --- a/cmd/config/main.go +++ b/cmd/config/main.go @@ -27,8 +27,7 @@ type Config struct { func Load(configFile string, config *Config) { if !common.IsFileExist(configFile) { // configure not exist -> load default - log.Infof("Load default configure -> %s", configFile) - common.WriteFile(configFile, defaultConfig, false) + loadDefaultConfig(configFile) } raw, err := os.ReadFile(configFile) // read configure content if err != nil {