Files
Adrian Zürcher f5e66af3d8 add new ip ping for udp device
add new function start and stop bus
2025-04-22 18:01:22 +02:00

63 lines
1.0 KiB
Go

package cfg
import (
"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 nil
}
b, err := os.ReadFile(p)
if err != nil {
return err
}
return yaml.Unmarshal(b, data)
}