Skip to content

Commit bc4ef3f

Browse files
committed
feat: allow configuring NewDecoder via callbacks
Since GH-59 was rejected on the basis that it wasn't useful enough to break the public API. I took a stab at an alternate solution that doesn't break the public API. While still allowing one to configure the decoder when defining it as a package global (as recommended by the README). ```go var decoder = NewDecoder(func(d *Decoder) { d.IgnoreUnknownKeys(true) }) ```
1 parent 8285576 commit bc4ef3f

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

decoder.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,12 @@ import (
1313
)
1414

1515
// NewDecoder returns a new Decoder.
16-
func NewDecoder() *Decoder {
17-
return &Decoder{cache: newCache()}
16+
func NewDecoder(options ...func(d *Decoder)) *Decoder {
17+
d := &Decoder{cache: newCache()}
18+
for _, opt := range options {
19+
opt(d)
20+
}
21+
return d
1822
}
1923

2024
// Decoder decodes values from a map[string][]string to a struct.

decoder_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2024,3 +2024,18 @@ func TestUnmashalPointerToEmbedded(t *testing.T) {
20242024
t.Errorf("Expected %v errors, got %v", expected, s.Value)
20252025
}
20262026
}
2027+
2028+
func TestNewDecoderWithOptions(t *testing.T) {
2029+
defaultEncoder := NewDecoder()
2030+
ignoreUnknownKeys := !defaultEncoder.ignoreUnknownKeys
2031+
2032+
decoder := NewDecoder(func(d *Decoder) {
2033+
d.IgnoreUnknownKeys(ignoreUnknownKeys)
2034+
})
2035+
2036+
if decoder.ignoreUnknownKeys != ignoreUnknownKeys {
2037+
t.Errorf("Expected ignoreUnknownKeys to be %t, got %t",
2038+
ignoreUnknownKeys,
2039+
decoder.ignoreUnknownKeys)
2040+
}
2041+
}

0 commit comments

Comments
 (0)