Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add MarshalToString #1875

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -1601,6 +1601,11 @@ func (v *Viper) SafeWriteConfigAs(filename string) error {
return v.writeConfig(filename, false)
}

// MarshalToString writes current configuration to a string
func MarshalToString(configTypeOps ...string) (string, error) {
return v.MarshalToString(configTypeOps...)
}

func (v *Viper) writeConfig(filename string, force bool) error {
v.logger.Info("attempting to write configuration to file")

Expand Down Expand Up @@ -1639,6 +1644,30 @@ func (v *Viper) writeConfig(filename string, force bool) error {
return f.Sync()
}

func (v *Viper) MarshalToString(configTypeOps ...string) (string, error) {
v.logger.Info("MarshalToString: attempting to marshal configuration to string")

//default by origin configType
var configType = v.configType
//set from param if configTypeOps len > 0
if len(configTypeOps) > 0 {
configType = configTypeOps[0]
}
if configType == "" {
return "", fmt.Errorf("MarshalToString: config type could not be determined")
}

if !stringInSlice(configType, SupportedExts) {
return "", UnsupportedConfigError(configType)
}

str, err := v.marshalToString(configType)
if err != nil {
return "", err
}
return str, nil
}

func (v *Viper) unmarshalReader(in io.Reader, c map[string]any) error {
buf := new(bytes.Buffer)
buf.ReadFrom(in)
Expand Down Expand Up @@ -1683,6 +1712,25 @@ func (v *Viper) marshalWriter(f afero.File, configType string) error {
return nil
}

// Marshal a map into string.
func (v *Viper) marshalToString(configType string) (string, error) {
c := v.AllSettings()
switch configType {
case "yaml", "yml", "json", "toml", "hcl", "tfvars", "ini", "prop", "props", "properties", "dotenv", "env":
encoder, err := v.encoderRegistry.Encoder(configType)
if err != nil {
return "", ConfigMarshalError{err}
}

b, err := encoder.Encode(c)
if err != nil {
return "", ConfigMarshalError{err}
}
return string(b), nil
}
return "", ConfigMarshalError{fmt.Errorf("config type could not be determined, type:%s", configType)}
}

func keyExists(k string, m map[string]any) string {
lk := strings.ToLower(k)
for mk := range m {
Expand Down