Switch configuration file from json to toml
This commit is contained in:
+34
-13
@@ -1,15 +1,18 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
SiteName string `json:"site_name"`
|
||||
Port string `json:"port"`
|
||||
DataDir string `json:"data_dir"`
|
||||
SiteName string `toml:"site_name"`
|
||||
Port string `toml:"port"`
|
||||
DataDir string `toml:"data_dir"`
|
||||
AdminUser string `toml:"admin_user"`
|
||||
AdminPasswordHash string `toml:"admin_password_hash"`
|
||||
}
|
||||
|
||||
func Load(path string) Config {
|
||||
@@ -19,18 +22,36 @@ func Load(path string) Config {
|
||||
DataDir: "data",
|
||||
}
|
||||
|
||||
file, err := os.Open(path)
|
||||
// Overwrite the default configuration (configData) with data from the file at 'path'
|
||||
_, err := toml.DecodeFile(path, &configData)
|
||||
if err != nil {
|
||||
log.Println("No config file found, using defaults. Consider setting up a Site Name at the very least!")
|
||||
return configData
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// Overwrite the default configuration with data from 'file'
|
||||
err = json.NewDecoder(file).Decode(&configData)
|
||||
if err != nil {
|
||||
log.Fatal("Config file exists but has errors:", err)
|
||||
}
|
||||
|
||||
return configData
|
||||
}
|
||||
|
||||
func Save(path string, configData Config) error {
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
log.Println("An error occured while trying to save configuration data.")
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
file.WriteString("site_name = \"" + configData.SiteName + "\"\n")
|
||||
file.WriteString("port = \"" + configData.Port + "\"\n")
|
||||
file.WriteString("data_dir = \"" + configData.DataDir + "\"\n")
|
||||
|
||||
if configData.AdminUser != "" {
|
||||
file.WriteString("admin_user = \"" + configData.AdminUser + "\"\n")
|
||||
file.WriteString("admin_password_hash = \"" + configData.AdminPasswordHash + "\"\n")
|
||||
file.WriteString("# This admin_password_hash above is a hashed password, not your actual\"")
|
||||
file.WriteString("# written password. You can't change your admin password here.\n")
|
||||
file.WriteString("# If you've lost your password, delete admin_user and admin_hash\n")
|
||||
file.WriteString("# from this file and restart the app to create a new account.\n")
|
||||
file.WriteString("# Your uploaded content will stay intact.\n")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user