45 lines
753 B
Go
45 lines
753 B
Go
package config
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
type Config struct {
|
|
fd *os.File
|
|
SoundVolume byte `json:"sound_volume"`
|
|
}
|
|
|
|
func DefaultConfig(fd *os.File) *Config {
|
|
cfg := Config{
|
|
SoundVolume: 255,
|
|
}
|
|
cfg.fd = fd
|
|
return &cfg
|
|
}
|
|
|
|
func LoadFromFile(filename string) (*Config, error) {
|
|
fd, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0o644)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
cfg := DefaultConfig(fd)
|
|
err = json.NewDecoder(fd).Decode(cfg)
|
|
return cfg, err
|
|
}
|
|
|
|
func (c Config) Save() error {
|
|
if err := c.fd.Truncate(0); err != nil {
|
|
return err
|
|
}
|
|
if _, err := c.fd.Seek(0, io.SeekStart); err != nil {
|
|
return err
|
|
}
|
|
return json.NewEncoder(c.fd).Encode(c)
|
|
}
|
|
|
|
func (c Config) Close() error {
|
|
return c.fd.Close()
|
|
}
|