Replace SetKeyDelimiter with functional options

This commit is contained in:
Mark Sagi-Kazar 2019-11-08 14:23:20 +01:00 committed by Márk Sági-Kazár
parent 9a405be5c0
commit a842b8f618
3 changed files with 36 additions and 14 deletions

View file

@ -667,8 +667,7 @@ If you want to unmarshal configuration where the keys themselves contain dot (th
you have to change the delimiter: you have to change the delimiter:
```go ```go
v := viper.New() v := viper.NewWithOptions(viper.KeyDelimiter("::"))
v.SetKeyDelimiter("::")
v.SetDefault("chart::values", map[string]interface{}{ v.SetDefault("chart::values", map[string]interface{}{
"ingress": map[string]interface{}{ "ingress": map[string]interface{}{

View file

@ -236,6 +236,39 @@ func New() *Viper {
return v return v
} }
// Option configures Viper using the functional options paradigm popularized by Rob Pike and Dave Cheney.
// If you're unfamiliar with this style,
// see https://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html and
// https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis.
type Option interface {
apply(v *Viper)
}
type optionFunc func(v *Viper)
func (fn optionFunc) apply(v *Viper) {
fn(v)
}
// KeyDelimiter sets the delimiter used for determining key parts.
// By default it's value is ".".
func KeyDelimiter(d string) Option {
return optionFunc(func(v *Viper) {
v.keyDelim = d
})
}
// NewWithOptions creates a new Viper instance.
func NewWithOptions(opts ...Option) *Viper {
v := New()
for _, opt := range opts {
opt.apply(v)
}
return v
}
// Reset is intended for testing, will reset all to default settings. // Reset is intended for testing, will reset all to default settings.
// In the public interface for the viper package so applications // In the public interface for the viper package so applications
// can use it in their testing as well. // can use it in their testing as well.
@ -245,15 +278,6 @@ func Reset() {
SupportedRemoteProviders = []string{"etcd", "consul"} SupportedRemoteProviders = []string{"etcd", "consul"}
} }
// SetKeyDelimiter sets the delimiter used for determining key parts.
// By default it's value is ".".
func SetKeyDelimiter(keyDelim string) { v.SetKeyDelimiter(keyDelim) }
func (v *Viper) SetKeyDelimiter(keyDelim string) {
if keyDelim != "" {
v.keyDelim = keyDelim
}
}
type defaultRemoteProvider struct { type defaultRemoteProvider struct {
provider string provider string
endpoint string endpoint string

View file

@ -2029,9 +2029,8 @@ emails:
active: true active: true
`) `)
func TestSetKeyDelimiter(t *testing.T) { func TestKeyDelimiter(t *testing.T) {
v := New() v := NewWithOptions(KeyDelimiter("::"))
v.SetKeyDelimiter("::")
v.SetConfigType("yaml") v.SetConfigType("yaml")
r := strings.NewReader(string(yamlExampleWithDot)) r := strings.NewReader(string(yamlExampleWithDot))