Skip to content

Commit

Permalink
Refinement: change the default behavior of reading default configurat…
Browse files Browse the repository at this point in the history
…ions (#346)

Co-authored-by: loyalsoldier <[email protected]>
  • Loading branch information
Sousa Chinensis and Loyalsoldier authored May 31, 2021
1 parent 907ebd6 commit d538823
Showing 1 changed file with 52 additions and 16 deletions.
68 changes: 52 additions & 16 deletions proxy/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,31 +23,67 @@ func (o *Option) Name() string {
return Name
}

func (o *Option) Handle() error {
data, err := ioutil.ReadFile(*o.path)
if err != nil {
log.Fatal(err)
}

func detectAndReadConfig(file string) ([]byte, bool, error) {
isJSON := false
switch {
case strings.HasSuffix(*o.path, ".json"):
case strings.HasSuffix(file, ".json"):
isJSON = true
case strings.HasSuffix(*o.path, ".yaml"), strings.HasSuffix(*o.path, ".yml"):
case strings.HasSuffix(file, ".yaml"), strings.HasSuffix(file, ".yml"):
isJSON = false
default:
log.Fatal("unsupported filename suffix", *o.path, ". use .yaml or .json instead.")
log.Fatalf("unsupported config format: %s. use .yaml or .json instead.", file)
}

log.Info("trojan-go", constant.Version, "initializing")
proxy, err := NewProxyFromConfigData(data, isJSON)
data, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
return nil, false, err
}
err = proxy.Run()
if err != nil {
log.Fatal(err)
return data, isJSON, nil
}

func (o *Option) Handle() error {
defaultConfigPath := []string{
"config.json",
"config.yml",
"config.yaml",
}

isJSON := false
var data []byte
var err error

switch *o.path {
case "":
log.Warn("no specified config file, use default path to detect config file")
for _, file := range defaultConfigPath {
log.Warn("try to load config from default path:", file)
data, isJSON, err = detectAndReadConfig(file)
if err != nil {
log.Warn(err)
continue
}
break
}
default:
data, isJSON, err = detectAndReadConfig(*o.path)
if err != nil {
log.Fatal(err)
}
}

if data != nil {
log.Info("trojan-go", constant.Version, "initializing")
proxy, err := NewProxyFromConfigData(data, isJSON)
if err != nil {
log.Fatal(err)
}
err = proxy.Run()
if err != nil {
log.Fatal(err)
}
}

log.Fatal("no valid config")
return nil
}

Expand All @@ -57,7 +93,7 @@ func (o *Option) Priority() int {

func init() {
option.RegisterHandler(&Option{
path: flag.String("config", "config.json", "Trojan-Go config filename (.yaml/.yml/.json)"),
path: flag.String("config", "", "Trojan-Go config filename (.yaml/.yml/.json)"),
})
option.RegisterHandler(&StdinOption{
format: flag.String("stdin-format", "disabled", "Read from standard input (yaml/json)"),
Expand Down

0 comments on commit d538823

Please sign in to comment.