-
Notifications
You must be signed in to change notification settings - Fork 37
/
utils.go
51 lines (39 loc) · 1.45 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package config
import (
"github.com/pelletier/go-toml/v2"
"github.com/pkg/errors"
"github.com/rs/zerolog"
)
// BytesToAnyTomlStruct unmarshals the given bytes into the given target struct, apart from unmarshalling the root
// it also looks for given configuration name and unmarshals it into the target struct overwriting the root.
// Target needs to be a struct with exported fields with `toml:"field_name"` tags.
func BytesToAnyTomlStruct(logger zerolog.Logger, filename, configurationName string, target any, content []byte) error {
err := toml.Unmarshal(content, target)
if err != nil {
return errors.Wrapf(err, "error unmarshaling config")
}
logger.Debug().Msgf("Successfully unmarshalled %s config file", filename)
var someToml map[string]interface{}
err = toml.Unmarshal(content, &someToml)
if err != nil {
return err
}
if configurationName == "" {
logger.Debug().Msgf("No configuration name provided, will read only default configuration.")
return nil
}
if _, ok := someToml[configurationName]; !ok {
logger.Debug().Msgf("Config file %s does not contain configuration named '%s', will read only default configuration.", filename, configurationName)
return nil
}
marshalled, err := toml.Marshal(someToml[configurationName])
if err != nil {
return err
}
err = toml.Unmarshal(marshalled, target)
if err != nil {
return err
}
logger.Debug().Msgf("Configuration named '%s' read successfully.", configurationName)
return nil
}