64 lines
1.1 KiB
Go
64 lines
1.1 KiB
Go
package cfg
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
type Cfg struct {
|
|
Name string
|
|
Dir string
|
|
}
|
|
|
|
// Initializes new config handler
|
|
// dir is config directory from working dir on
|
|
// name is filename, file extention is automatically added '.cfg'
|
|
// file is in yaml format
|
|
// if file exists it will read its content in to the driver
|
|
func NewCfgHandler(dir, name string) *Cfg {
|
|
return &Cfg{
|
|
Dir: dir,
|
|
Name: name,
|
|
}
|
|
}
|
|
|
|
func (c *Cfg) SaveCfg(data any) error {
|
|
if _, err := os.Stat(c.Dir); err != nil {
|
|
if err := os.MkdirAll(c.Dir, 0666); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
f, err := os.Create(path.Join(c.Dir, c.Name) + ".cfg")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
|
|
encoder := yaml.NewEncoder(f)
|
|
encoder.SetIndent(2)
|
|
|
|
if err := encoder.Encode(data); err != nil {
|
|
return err
|
|
}
|
|
encoder.Close()
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c *Cfg) LoadCfg(data any) error {
|
|
p := path.Join(c.Dir, c.Name) + ".cfg"
|
|
if _, err := os.Stat(p); err != nil {
|
|
return fmt.Errorf("no configuration file: '%s' found", p)
|
|
}
|
|
|
|
b, err := os.ReadFile(p)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return yaml.Unmarshal(b, data)
|
|
}
|