diff --git a/config.go b/config.go index d7880c7..e601134 100644 --- a/config.go +++ b/config.go @@ -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 { diff --git a/util.go b/util.go index bc3bcc3..4a09872 100644 --- a/util.go +++ b/util.go @@ -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)