GoBroke/conf/funcs.go
2024-12-17 17:39:10 -05:00

76 lines
1.3 KiB
Go

package conf
import (
`encoding/json`
"github.com/BurntSushi/toml"
"github.com/creasty/defaults"
"github.com/goccy/go-yaml"
"r00t2.io/sysutils/paths"
)
func NewConfig(path string) (cfg *Config, err error) {
var b []byte
if err = paths.RealPath(&path); err != nil {
return
}
cfg, err = NewConfigFromBytes(b)
return
}
func NewConfigFromBytes(b []byte) (cfg *Config, err error) {
if err = json.Unmarshal(b, &cfg); err != nil {
if err = yaml.Unmarshal(b, &cfg); err != nil {
if err = toml.Unmarshal(b, &cfg); err != nil {
if err = toml.Unmarshal(b, &cfg); err != nil {
err = ErrUnkownSyntax
return
}
}
}
}
if err = defaults.Set(cfg); err != nil {
return
}
if cfg.CacheDB != ":memory:" {
if err = paths.RealPath(&cfg.CacheDB); err != nil {
return
}
}
if err = validate.Struct(cfg); err != nil {
return
}
for _, t := range cfg.Tunnels {
t.cfg = cfg
if t.Username == nil {
if cfg.Username == nil {
err = ErrMissingUser
return
} else {
t.Username = cfg.Username
}
}
if t.TemplateConfigs != nil && len(t.TemplateConfigs) > 0 {
for _, tpl := range t.TemplateConfigs {
if err = paths.RealPath(&tpl.Template); err != nil {
return
}
if err = paths.RealPath(&tpl.Dest); err != nil {
return
}
}
}
}
return
}