104 lines
2.0 KiB
Go
104 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
toml "github.com/pelletier/go-toml/v2"
|
|
"io/ioutil"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
type Config struct {
|
|
Address string
|
|
Port int
|
|
ScanDirectory string
|
|
//Age int
|
|
//Cats []string
|
|
//Pi float64
|
|
//Perfection []int
|
|
//DOB time.Time // requires `import time`
|
|
}
|
|
|
|
func get_config_dir() 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 get_config(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, err
|
|
}
|
|
|
|
config_path := filepath.Join(config_dir, "server.toml")
|
|
|
|
fmt.Printf("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, err
|
|
}
|
|
|
|
fi, err := config_file.Stat()
|
|
if err != nil {
|
|
return &config, err
|
|
}
|
|
|
|
if fi.Size() == 0 {
|
|
// if file is empty, write default config
|
|
data, err := toml.Marshal(config)
|
|
if err != nil {
|
|
return &config, 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, err
|
|
}
|
|
err = toml.Unmarshal(data, &config)
|
|
if err != nil {
|
|
return &config, err
|
|
}
|
|
return &config, nil
|
|
}
|
|
|
|
}
|
|
|
|
func main() {
|
|
|
|
config_dir := get_config_dir()
|
|
|
|
config, err := get_config(config_dir)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if config == nil {
|
|
fmt.Printf("Created config file at %v, please edit and launch again\n", config_dir)
|
|
} else {
|
|
fmt.Printf("Config: %v\n", config)
|
|
}
|
|
|
|
}
|