Browse Source

feat: default config with json or toml format

v1.x.x
Dnomd343 2 years ago
parent
commit
f13b310d52
  1. 44
      cmd/config/default.go
  2. 3
      cmd/config/main.go

44
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)
}

3
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 {

Loading…
Cancel
Save