Skip to content
This repository was archived by the owner on Jul 22, 2024. It is now read-only.

Commit 740c764

Browse files
committed
WeakDecode
1 parent 6fb2c83 commit 740c764

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

mapstructure.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,23 @@ func Decode(m interface{}, rawVal interface{}) error {
104104
return decoder.Decode(m)
105105
}
106106

107+
// WeakDecode is the same as Decode but is shorthand to enable
108+
// WeaklyTypedInput. See DecoderConfig for more info.
109+
func WeakDecode(input, output interface{}) error {
110+
config := &DecoderConfig{
111+
Metadata: nil,
112+
Result: output,
113+
WeaklyTypedInput: true,
114+
}
115+
116+
decoder, err := NewDecoder(config)
117+
if err != nil {
118+
return err
119+
}
120+
121+
return decoder.Decode(input)
122+
}
123+
107124
// NewDecoder returns a new decoder for the given configuration. Once
108125
// a decoder has been returned, the same configuration must not be used
109126
// again.

mapstructure_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -775,6 +775,30 @@ func TestTagged(t *testing.T) {
775775
}
776776
}
777777

778+
func TestWeakDecode(t *testing.T) {
779+
t.Parallel()
780+
781+
input := map[string]interface{}{
782+
"foo": "4",
783+
"bar": "value",
784+
}
785+
786+
var result struct {
787+
Foo int
788+
Bar string
789+
}
790+
791+
if err := WeakDecode(input, &result); err != nil {
792+
t.Fatalf("err: %s", err)
793+
}
794+
if result.Foo != 4 {
795+
t.Fatalf("bad: %#v", result)
796+
}
797+
if result.Bar != "value" {
798+
t.Fatalf("bad: %#v", result)
799+
}
800+
}
801+
778802
func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) {
779803
var result Slice
780804
err := Decode(input, &result)

0 commit comments

Comments
 (0)