13 "github.com/iotbzh/xds-server/lib/common"
16 type SyncThingConf struct {
17 BinDir string `json:"binDir"`
18 Home string `json:"home"`
19 GuiAddress string `json:"gui-address"`
20 GuiAPIKey string `json:"gui-apikey"`
23 type FileConfig struct {
24 WebAppDir string `json:"webAppDir"`
25 ShareRootDir string `json:"shareRootDir"`
26 SdkRootDir string `json:"sdkRootDir"`
27 HTTPPort string `json:"httpPort"`
28 SThgConf *SyncThingConf `json:"syncthing"`
29 LogsDir string `json:"logsDir"`
32 // getConfigFromFile reads configuration from a config file.
33 // Order to determine which config file is used:
34 // 1/ from command line option: "--config myConfig.json"
35 // 2/ $HOME/.xds/config.json file
36 // 3/ <current_dir>/config.json file
37 // 4/ <xds-server executable dir>/config.json file
39 func updateConfigFromFile(c *Config, confFile string) error {
41 searchIn := make([]string, 0, 3)
43 searchIn = append(searchIn, confFile)
45 if usr, err := user.Current(); err == nil {
46 searchIn = append(searchIn, path.Join(usr.HomeDir, ".xds", "config.json"))
48 cwd, err := os.Getwd()
50 searchIn = append(searchIn, path.Join(cwd, "config.json"))
52 exePath, err := filepath.Abs(filepath.Dir(os.Args[0]))
54 searchIn = append(searchIn, path.Join(exePath, "config.json"))
58 for _, p := range searchIn {
59 if _, err := os.Stat(p); err == nil {
65 // No config file found
69 c.Log.Infof("Use config file: %s", *cFile)
71 // TODO move on viper package to support comments in JSON and also
72 // bind with flags (command line options)
73 // see https://github.com/spf13/viper#working-with-flags
75 fd, _ := os.Open(*cFile)
78 if err := json.NewDecoder(fd).Decode(&fCfg); err != nil {
83 // Support environment variables (IOW ${MY_ENV_VAR} syntax) in config.json
84 for _, field := range []*string{
89 &fCfg.SThgConf.Home} {
91 rep, err := resolveEnvVar(*field)
95 *field = path.Clean(rep)
98 // Config file settings overwrite default config
100 if fCfg.WebAppDir != "" {
101 c.WebAppDir = strings.Trim(fCfg.WebAppDir, " ")
103 // Is it a full path ?
104 if !strings.HasPrefix(c.WebAppDir, "/") && exePath != "" {
105 // Check first from current directory
106 for _, rootD := range []string{cwd, exePath} {
107 ff := path.Join(rootD, c.WebAppDir, "index.html")
108 if common.Exists(ff) {
109 c.WebAppDir = path.Join(rootD, c.WebAppDir)
115 if fCfg.ShareRootDir != "" {
116 c.ShareRootDir = fCfg.ShareRootDir
119 if fCfg.HTTPPort != "" {
120 c.HTTPPort = fCfg.HTTPPort
126 // resolveEnvVar Resolved environment variable regarding the syntax ${MYVAR}
127 func resolveEnvVar(s string) (string, error) {
128 re := regexp.MustCompile("\\${(.*)}")
129 vars := re.FindAllStringSubmatch(s, -1)
131 for _, v := range vars {
132 val := os.Getenv(v[1])
134 return res, fmt.Errorf("ERROR: %s env variable not defined", v[1])
137 rer := regexp.MustCompile("\\${" + v[1] + "}")
138 res = rer.ReplaceAllString(res, val)