13 type SyncThingConf struct {
14 Home string `json:"home"`
15 GuiAddress string `json:"gui-address"`
16 GuiAPIKey string `json:"gui-apikey"`
19 type FileConfig struct {
20 WebAppDir string `json:"webAppDir"`
21 ShareRootDir string `json:"shareRootDir"`
22 HTTPPort string `json:"httpPort"`
23 SThgConf SyncThingConf `json:"syncthing"`
26 // getConfigFromFile reads configuration from a config file.
27 // Order to determine which config file is used:
28 // 1/ from command line option: "--config myConfig.json"
29 // 2/ $HOME/.xds/config.json file
30 // 3/ <xds-server executable dir>/config.json file
32 func updateConfigFromFile(c *Config, confFile string) error {
34 searchIn := make([]string, 0, 3)
36 searchIn = append(searchIn, confFile)
38 if usr, err := user.Current(); err == nil {
39 searchIn = append(searchIn, path.Join(usr.HomeDir, ".xds", "config.json"))
41 cwd, err := os.Getwd()
43 searchIn = append(searchIn, path.Join(cwd, "config.json"))
45 exePath, err := filepath.Abs(filepath.Dir(os.Args[0]))
47 searchIn = append(searchIn, path.Join(exePath, "config.json"))
51 for _, p := range searchIn {
52 if _, err := os.Stat(p); err == nil {
58 // No config file found
62 // TODO move on viper package to support comments in JSON and also
63 // bind with flags (command line options)
64 // see https://github.com/spf13/viper#working-with-flags
66 fd, _ := os.Open(*cFile)
69 if err := json.NewDecoder(fd).Decode(&fCfg); err != nil {
74 // Support environment variables (IOW ${MY_ENV_VAR} syntax) in config.json
75 // TODO: better to use reflect package to iterate on fields and be more generic
76 fCfg.WebAppDir = path.Clean(resolveEnvVar(fCfg.WebAppDir))
77 fCfg.ShareRootDir = path.Clean(resolveEnvVar(fCfg.ShareRootDir))
78 fCfg.SThgConf.Home = path.Clean(resolveEnvVar(fCfg.SThgConf.Home))
80 // Config file settings overwrite default config
82 if fCfg.WebAppDir != "" {
83 c.WebAppDir = strings.Trim(fCfg.WebAppDir, " ")
85 // Is it a full path ?
86 if !strings.HasPrefix(c.WebAppDir, "/") && exePath != "" {
87 // Check first from current directory
88 for _, rootD := range []string{cwd, exePath} {
89 ff := path.Join(rootD, c.WebAppDir, "index.html")
91 c.WebAppDir = path.Join(rootD, c.WebAppDir)
97 if fCfg.ShareRootDir != "" {
98 c.ShareRootDir = fCfg.ShareRootDir
101 if fCfg.HTTPPort != "" {
102 c.HTTPPort = fCfg.HTTPPort
108 // resolveEnvVar Resolved environment variable regarding the syntax ${MYVAR}
109 func resolveEnvVar(s string) string {
110 re := regexp.MustCompile("\\${(.*)}")
111 vars := re.FindAllStringSubmatch(s, -1)
113 for _, v := range vars {
114 val := os.Getenv(v[1])
116 rer := regexp.MustCompile("\\${" + v[1] + "}")
117 res = rer.ReplaceAllString(res, val)
123 // exists returns whether the given file or directory exists or not
124 func exists(path string) bool {
125 _, err := os.Stat(path)
129 if os.IsNotExist(err) {