Refactor application into multiple files
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/op/go-logging"
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
)
|
||||
|
||||
var log = logging.MustGetLogger("ikinuki-server")
|
||||
|
||||
type Config struct {
|
||||
Address string
|
||||
Port int
|
||||
ScanDirectory string
|
||||
}
|
||||
|
||||
|
||||
func GetConfigDir() string {
|
||||
// Find config directory
|
||||
|
||||
// Linux (XDG base directory specification compliant)
|
||||
xdg_config_home := os.Getenv("XDG_CONFIG_HOME")
|
||||
|
||||
if xdg_config_home != "" {
|
||||
return filepath.Join(xdg_config_home, "ikinuki")
|
||||
} else {
|
||||
home := os.Getenv("HOME")
|
||||
return filepath.Join(home, ".config", "ikinuki")
|
||||
}
|
||||
}
|
||||
|
||||
func GetConfig(config_dir string) (*Config, error) {
|
||||
config := Config{
|
||||
Address: "127.0.0.1",
|
||||
Port: 32520,
|
||||
ScanDirectory: "FILL IN",
|
||||
}
|
||||
|
||||
err := os.MkdirAll(config_dir, 0755)
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not create config directory: %v", err)
|
||||
}
|
||||
|
||||
config_path := filepath.Join(config_dir, "server.toml")
|
||||
|
||||
log.Debugf("Config File Dir: %v\n", config_path)
|
||||
|
||||
// open file, creating it if empty
|
||||
config_file, err := os.OpenFile(config_path, os.O_RDWR|os.O_CREATE, 0755)
|
||||
defer config_file.Close()
|
||||
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not open config file: %v", err)
|
||||
}
|
||||
|
||||
fi, err := config_file.Stat()
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not get config file size: %v", err)
|
||||
}
|
||||
|
||||
if fi.Size() == 0 {
|
||||
// if file is empty, write default config
|
||||
data, err := toml.Marshal(config)
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not write default config to file: %v", err)
|
||||
}
|
||||
config_file.Write(data)
|
||||
// return nil as the user must edit the config file
|
||||
return nil, nil
|
||||
} else {
|
||||
// try to parse config file
|
||||
data, err := ioutil.ReadAll(config_file)
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not read data from config file: %v", err)
|
||||
}
|
||||
err = toml.Unmarshal(data, &config)
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not parse config file contents: %v", err)
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user