2018-11-19 21:36:21 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
2019-06-13 19:25:32 +00:00
|
|
|
"encoding/json"
|
2018-11-19 21:36:21 +00:00
|
|
|
"fmt"
|
|
|
|
"os"
|
2019-03-01 13:56:49 +00:00
|
|
|
"path/filepath"
|
2019-02-17 17:23:59 +00:00
|
|
|
"regexp"
|
2018-11-19 21:36:21 +00:00
|
|
|
)
|
|
|
|
|
2019-02-17 17:23:59 +00:00
|
|
|
var validUUID = regexp.MustCompile("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
|
|
|
|
|
|
|
|
// Read the configuration file
|
2019-06-13 19:25:32 +00:00
|
|
|
func Read(configFile string) (*Configuration, error) {
|
2018-11-19 21:36:21 +00:00
|
|
|
|
2019-06-13 19:25:32 +00:00
|
|
|
fc := &Configuration{}
|
2018-11-19 21:36:21 +00:00
|
|
|
|
2019-02-17 17:23:59 +00:00
|
|
|
f, err := os.Open(configFile)
|
2018-11-19 21:36:21 +00:00
|
|
|
if err != nil {
|
2019-02-17 17:23:59 +00:00
|
|
|
return nil, fmt.Errorf("Can not open file %v: %v", configFile, err)
|
2018-11-19 21:36:21 +00:00
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
2019-06-13 19:25:32 +00:00
|
|
|
jsonDecoder := json.NewDecoder(f)
|
|
|
|
if err := jsonDecoder.Decode(&fc); err != nil {
|
|
|
|
return nil, fmt.Errorf("Can not unmarshal JSON: %v", err)
|
2018-11-28 11:54:14 +00:00
|
|
|
}
|
|
|
|
|
2019-02-17 17:23:59 +00:00
|
|
|
return fc, nil
|
2018-11-28 11:54:14 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
|
2019-02-17 17:23:59 +00:00
|
|
|
// Write the configuration into a file, specified by the configuration filepath
|
2019-06-13 19:25:32 +00:00
|
|
|
func Write(cfg *Configuration, configFile string) error {
|
2018-11-28 11:54:14 +00:00
|
|
|
|
2019-03-01 13:56:49 +00:00
|
|
|
if _, err := os.Stat(configFile); os.IsNotExist(err) {
|
|
|
|
configDir := filepath.Dir(configFile)
|
|
|
|
err := os.MkdirAll(configDir, os.ModeDir)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Can not create config directory %v: %v", configDir, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-17 17:23:59 +00:00
|
|
|
f, err := os.Create(configFile)
|
2018-11-28 11:54:14 +00:00
|
|
|
if err != nil {
|
2019-03-01 13:56:49 +00:00
|
|
|
return fmt.Errorf("Can not write config file: %v", err)
|
2018-11-28 11:54:14 +00:00
|
|
|
}
|
2019-02-17 17:23:59 +00:00
|
|
|
defer f.Close()
|
2018-11-28 11:54:14 +00:00
|
|
|
|
2019-06-13 19:25:32 +00:00
|
|
|
encoder := json.NewEncoder(f)
|
|
|
|
encoder.SetIndent("", " ")
|
|
|
|
err = encoder.Encode(cfg)
|
2018-11-19 21:36:21 +00:00
|
|
|
if err != nil {
|
2019-06-13 19:25:32 +00:00
|
|
|
return fmt.Errorf("Error in encoding struct to json: %v", err)
|
2018-11-19 21:36:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2019-02-17 17:23:59 +00:00
|
|
|
|
2018-11-19 21:36:21 +00:00
|
|
|
}
|