dorfylegends/backend/server/config.go

80 lines
1.2 KiB
Go
Raw Normal View History

2022-05-01 13:29:39 +03:00
package server
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
type Config struct {
2022-05-05 13:55:33 +03:00
path string
LastPath string
LastFile string
DebugTemplates bool `json:"DebugTemplates,omitempty"`
2022-05-01 13:29:39 +03:00
}
2022-05-05 13:55:33 +03:00
func LoadConfig(path string) (*Config, error) {
var err error
if path == "" {
path, err = configPath()
if err != nil {
return nil, err
}
2022-05-01 13:29:39 +03:00
}
data, err := ioutil.ReadFile(path)
if err != nil {
fmt.Println("OPEN", err)
if os.IsNotExist(err) {
fmt.Println("EX", err)
home, err := os.UserHomeDir()
if err != nil {
return nil, err
}
2022-05-05 13:55:33 +03:00
return &Config{LastPath: home, path: path}, nil
2022-05-01 13:29:39 +03:00
} else {
return nil, err
}
}
c := &Config{}
json.Unmarshal(data, c)
2022-05-05 13:55:33 +03:00
c.path = path
2022-05-01 13:29:39 +03:00
return c, nil
}
func (c *Config) Save() error {
2022-05-05 13:55:33 +03:00
var err error
path := c.path
if path == "" {
path, err = configPath()
if err != nil {
return err
}
2022-05-01 13:29:39 +03:00
}
file, err := json.MarshalIndent(c, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(path, file, 0644)
}
func configPath() (string, error) {
path, err := os.UserHomeDir()
if err != nil {
return "", err
}
path = filepath.Join(path, ".legendsbrowser")
os.MkdirAll(path, os.ModePerm)
return filepath.Join(path, "config.json"), nil
}