diff --git a/proxy/option.go b/proxy/option.go index 7a0b139e4..978b88f8d 100644 --- a/proxy/option.go +++ b/proxy/option.go @@ -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 } @@ -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)"),