From 8f2b31b008e95a8a40c1c5ce75b7c5e93e08a300 Mon Sep 17 00:00:00 2001 From: "Lubomir I. Ivanov" Date: Fri, 2 Nov 2018 17:45:52 +0200 Subject: [PATCH] UnmarshalStrict: use DisallowUnknownFields Without this option the JSON decoder would tolerate unknown fields. --- yaml.go | 2 +- yaml_test.go | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/yaml.go b/yaml.go index ec24ab5..457c9de 100644 --- a/yaml.go +++ b/yaml.go @@ -39,7 +39,7 @@ func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error { // UnmarshalStrict strictly converts YAML to JSON then uses JSON to unmarshal // into an object, optionally configuring the behavior of the JSON unmarshal. func UnmarshalStrict(y []byte, o interface{}, opts ...JSONOpt) error { - return yamlUnmarshal(y, o, true, opts...) + return yamlUnmarshal(y, o, true, append(opts, DisallowUnknownFields)...) } // yamlUnmarshal unmarshals the given YAML byte stream into the given interface, diff --git a/yaml_test.go b/yaml_test.go index ad6b2e0..42a2315 100644 --- a/yaml_test.go +++ b/yaml_test.go @@ -211,6 +211,15 @@ a: `) s4 := NamedThing{} unmarshalStrictFail(t, y, &s4) + + // Strict unmarshal should fail for unknown fields + y = []byte(` +name: TestB +id: ID-B +unknown: Some-Value +`) + s5 := NamedThing{} + unmarshalStrictFail(t, y, &s5) } func unmarshalStrict(t *testing.T, y []byte, s, e interface{}, opts ...JSONOpt) {