event-gateway/internal/config/file.go

71 lines
1.4 KiB
Go

// Copyright © 2023 Roberto Hidalgo <event-gateway@un.rob.mx>
// SPDX-License-Identifier: Apache-2.0
package config
import (
"encoding/json"
"fmt"
"io/fs"
"os"
"os/signal"
"syscall"
"git.rob.mx/nidito/chinampa/pkg/logger"
)
var flog = logger.Sub("event-gateway.config.file")
var FS fs.FS
type fileSchema map[string]*Listener
type File struct {
Path string
}
var _ Loader = &File{}
func (l *File) String() string {
return fmt.Sprintf("FileLoader at %s", l.Path)
}
func (l *File) Load() (res []*Listener, err error) {
var data []byte
if FS != nil {
data, err = fs.ReadFile(FS, l.Path)
} else {
data, err = os.ReadFile(l.Path)
}
if err != nil {
return res, fmt.Errorf("could not read %s: %s", l.Path, err)
}
config := &fileSchema{}
if err := json.Unmarshal(data, &config); err != nil {
return res, fmt.Errorf("could not unserialize %s as json: %s", l.Path, err)
}
for name, listener := range *config {
listener.ID = name
res = append(res, listener)
}
return res, nil
}
func (l *File) Watch(reg chan []*Listener) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP)
go func() {
for {
<-c
flog.Info("SIGHUP detected, reloading file configuration")
res, err := l.Load()
if err != nil {
flog.Errorf("could not reload file configuration: %s", err)
}
flog.Info("Reloaded file configuration, updating listeners")
reg <- res
}
}()
}