Skip to content

Commit ae564f0

Browse files
committed
feat: add function to write config to writer
Signed-off-by: Mark Sagi-Kazar <[email protected]>
1 parent 3268cbd commit ae564f0

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

viper.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1591,6 +1591,19 @@ func (v *Viper) WriteConfigAs(filename string) error {
15911591
return v.writeConfig(filename, true)
15921592
}
15931593

1594+
// WriteConfigTo writes current configuration to an [io.Writer].
1595+
func WriteConfigTo(w io.Writer) error { return v.WriteConfigTo(w) }
1596+
1597+
func (v *Viper) WriteConfigTo(w io.Writer) error {
1598+
format := strings.ToLower(v.getConfigType())
1599+
1600+
if !slices.Contains(SupportedExts, format) {
1601+
return UnsupportedConfigError(format)
1602+
}
1603+
1604+
return v.marshalWriter(w, format)
1605+
}
1606+
15941607
// SafeWriteConfigAs writes current configuration to a given filename if it does not exist.
15951608
func SafeWriteConfigAs(filename string) error { return v.SafeWriteConfigAs(filename) }
15961609

@@ -1665,7 +1678,7 @@ func (v *Viper) unmarshalReader(in io.Reader, c map[string]any) error {
16651678
}
16661679

16671680
// Marshal a map into Writer.
1668-
func (v *Viper) marshalWriter(f afero.File, configType string) error {
1681+
func (v *Viper) marshalWriter(w io.Writer, configType string) error {
16691682
c := v.AllSettings()
16701683

16711684
encoder, err := v.encoderRegistry.Encoder(configType)
@@ -1678,7 +1691,7 @@ func (v *Viper) marshalWriter(f afero.File, configType string) error {
16781691
return ConfigMarshalError{err}
16791692
}
16801693

1681-
_, err = f.WriteString(string(b))
1694+
_, err = w.Write(b)
16821695
if err != nil {
16831696
return ConfigMarshalError{err}
16841697
}

0 commit comments

Comments
 (0)