93 lines
2.3 KiB
Go
93 lines
2.3 KiB
Go
package configurator
|
|
|
|
import (
|
|
"errors"
|
|
"sync"
|
|
|
|
"git.belvedersky.ru/common/configurator/providers"
|
|
"git.belvedersky.ru/common/configurator/providers/file"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type ConfiguratorService struct {
|
|
Config interface{} // Конфигурация
|
|
Configurator interface{} // Конфигуратор *viper.Viper
|
|
provider providers.ProviderType // Провайдер конфигурации
|
|
providerConfig interface{} // Конфигурация провайдера
|
|
l *sync.RWMutex //
|
|
}
|
|
|
|
// Создание нового сервиса конфигураций
|
|
func New(provider providers.ProviderType, providerConfig, cfg interface{}) (config *ConfiguratorService, err error) {
|
|
c := ConfiguratorService{}
|
|
|
|
c.Config = cfg
|
|
c.provider = provider
|
|
c.providerConfig = providerConfig
|
|
c.l = new(sync.RWMutex)
|
|
|
|
switch provider {
|
|
case providers.FILE:
|
|
|
|
fileName := providerConfig.(providers.FileConfig).FileName
|
|
config, err := file.Load(fileName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if err := config.Unmarshal(&c.Config); err != nil {
|
|
return nil, err
|
|
}
|
|
c.Configurator = config
|
|
default:
|
|
return nil, errors.New("no other providers yet")
|
|
|
|
}
|
|
return &c, nil
|
|
}
|
|
|
|
// Обновление конфигрурации
|
|
func (c *ConfiguratorService) Update(cfg interface{}) (new interface{}, err error) {
|
|
|
|
switch c.provider {
|
|
case providers.FILE:
|
|
if cfg != nil {
|
|
c.l.Lock()
|
|
c.Config = cfg
|
|
c.l.Unlock()
|
|
}
|
|
if err := c.Configurator.(*viper.Viper).Unmarshal(&cfg); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := file.WriteToFile(c.providerConfig.(providers.FileConfig).FileName, c.Config); err != nil {
|
|
return nil, err
|
|
}
|
|
default:
|
|
err = errors.New("provider not found")
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
// Получение значения
|
|
func (c *ConfiguratorService) Get(key string) (value interface{}, err error) {
|
|
switch c.provider {
|
|
case providers.FILE:
|
|
value = c.Configurator.(*viper.Viper).Get(key)
|
|
default:
|
|
err = errors.New("provider not found")
|
|
}
|
|
return
|
|
}
|
|
|
|
// Изменение значения
|
|
func (c *ConfiguratorService) Set(key string, value interface{}) (err error) {
|
|
switch c.provider {
|
|
case providers.FILE:
|
|
c.Configurator.(*viper.Viper).Set(key, value)
|
|
default:
|
|
err = errors.New("provider not found")
|
|
}
|
|
return
|
|
}
|