2020-11-08 17:19:25 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
2021-11-18 19:36:07 +00:00
|
|
|
"path/filepath"
|
2020-11-08 17:19:25 +00:00
|
|
|
|
2021-03-01 16:43:28 +00:00
|
|
|
"github.com/distribyted/distribyted"
|
2020-11-08 17:19:25 +00:00
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
)
|
|
|
|
|
|
|
|
type EventFunc func(event string)
|
|
|
|
type ReloadFunc func(*Root, EventFunc) error
|
|
|
|
|
|
|
|
type Handler struct {
|
2021-11-16 12:13:58 +00:00
|
|
|
p string
|
2020-11-08 17:19:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewHandler(path string) *Handler {
|
|
|
|
return &Handler{p: path}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Handler) createFromTemplateFile() ([]byte, error) {
|
2021-11-21 17:31:47 +00:00
|
|
|
t, err := distribyted.Templates.Open("templates/config_template.yaml")
|
2020-11-08 17:19:25 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer t.Close()
|
|
|
|
|
|
|
|
tb, err := ioutil.ReadAll(t)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-11-18 19:36:07 +00:00
|
|
|
if err := os.MkdirAll(filepath.Dir(c.p), 0744); err != nil {
|
2020-11-08 17:19:25 +00:00
|
|
|
return nil, fmt.Errorf("error creating path for configuration file: %s, %w", c.p, err)
|
|
|
|
}
|
|
|
|
return tb, ioutil.WriteFile(c.p, tb, 0644)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Handler) GetRaw() ([]byte, error) {
|
|
|
|
f, err := ioutil.ReadFile(c.p)
|
|
|
|
if os.IsNotExist(err) {
|
2021-11-20 19:57:25 +00:00
|
|
|
fmt.Println("configuration file does not exist, creating from template file:", c.p)
|
2020-11-08 17:19:25 +00:00
|
|
|
return c.createFromTemplateFile()
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error reading configuration file: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return f, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Handler) Get() (*Root, error) {
|
|
|
|
b, err := c.GetRaw()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
conf := &Root{}
|
|
|
|
if err := yaml.Unmarshal(b, conf); err != nil {
|
|
|
|
return nil, fmt.Errorf("error parsing configuration file: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
conf = AddDefaults(conf)
|
|
|
|
|
|
|
|
return conf, nil
|
|
|
|
}
|