This commit is contained in:
crusader 2017-08-30 20:28:19 +09:00
parent e413bd0bf6
commit d7879b0149
2 changed files with 45 additions and 0 deletions

View File

@ -81,6 +81,7 @@ type Configurator interface {
UnmarshalKey(key string, rawVal interface{}) error
Unmarshal(rawVal interface{}) error
UnmarshalExact(rawVal interface{}) error
Marshal(configType string) ([]byte, error)
BindPFlags(flags *pflag.FlagSet) error
BindPFlag(key string, flag *pflag.Flag) error
BindFlagValues(flags FlagValueSet) (err error)
@ -594,6 +595,13 @@ func (c *configurator) searchMap(source map[string]interface{}, path []string) i
return nil
}
// Marshal marshals the config to []byte.
func Marshal(configType string) ([]byte, error) { return _c.Marshal(configType) }
func (c *configurator) Marshal(configType string) ([]byte, error) {
return marshallConfig(c.config, configType)
}
// UnmarshalKey takes a single key and unmarshals it into a Struct.
func UnmarshalKey(key string, rawVal interface{}) error { return _c.UnmarshalKey(key, rawVal) }
func (c *configurator) UnmarshalKey(key string, rawVal interface{}) error {

37
util.go
View File

@ -28,6 +28,16 @@ func (pe ConfigParseError) Error() string {
return fmt.Sprintf("While parsing config: %s", pe.err.Error())
}
// ConfigMarshalError denotes failing to marshal configuration.
type ConfigMarshalError struct {
err error
}
// Error returns the formatted marshal error.
func (me ConfigMarshalError) Error() string {
return fmt.Sprintf("While marshaling config: %s", me.err.Error())
}
func absPathify(inPath string) (string, error) {
if strings.HasPrefix(inPath, "$HOME") {
inPath = userHomeDir() + inPath[5:]
@ -81,6 +91,33 @@ func exists(path string) (bool, error) {
return false, err
}
func marshallConfig(c map[string]interface{}, configType string) ([]byte, error) {
var (
buf []byte
err error
)
switch strings.ToLower(configType) {
case "yaml", "yml":
if buf, err = yaml.Marshal(c); err != nil {
return nil, ConfigMarshalError{err}
}
case "json":
if buf, err = json.Marshal(c); err != nil {
return nil, ConfigMarshalError{err}
}
case "toml":
if buf, err = toml.Marshal(c); err != nil {
return nil, ConfigMarshalError{err}
}
}
return buf, nil
}
func unmarshallConfigReader(in io.Reader, c map[string]interface{}, configType string) error {
buf := new(bytes.Buffer)
buf.ReadFrom(in)