dorfylegends/backend/server/config.go

81 lines
1.3 KiB
Go
Raw Permalink Normal View History

2022-05-01 13:29:39 +03:00
package server
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
)
type Config struct {
2022-05-05 13:55:33 +03:00
path string
LastPath string
LastFile string
2022-05-09 18:20:31 +03:00
Port int `json:"-"`
ServerMode bool `json:"-"`
SubUri string `json:"-"`
DebugTemplates bool `json:"DebugTemplates,omitempty"`
DebugJSON bool `json:"DebugJSON,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 {
if os.IsNotExist(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
}