From 70f441bc49afa4e9d10c27d7ed5733c4df7bddd3 Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Tue, 5 Dec 2017 22:38:36 -0800 Subject: encoding/json: error when trying to set an embedded pointer to unexported struct types This CL reverts CL 76851 and takes a different approach to #21357. The changes in encode.go and encode_test.go are reverts that rolls back the changed behavior in CL 76851 where embedded pointers to unexported struct types were unilaterally ignored in both marshal and unmarshal. Instead, these fields are handled as before with the exception that it returns an error when Unmarshal is unable to set an unexported field. The behavior of Marshal is now unchanged with regards to #21357. This policy maintains the greatest degree of backwards compatibility and avoids silently discarding data the user may have expected to be present. Fixes #21357 Change-Id: I7dc753280c99f786ac51acf7e6c0246618c8b2b1 Reviewed-on: https://go-review.googlesource.com/82135 Run-TryBot: Joe Tsai TryBot-Result: Gobot Gobot Reviewed-by: Ian Lance Taylor --- src/encoding/json/encode.go | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) (limited to 'src/encoding/json/encode.go') diff --git a/src/encoding/json/encode.go b/src/encoding/json/encode.go index 0522c43495..1e45e445d9 100644 --- a/src/encoding/json/encode.go +++ b/src/encoding/json/encode.go @@ -1094,18 +1094,11 @@ func typeFields(t reflect.Type) []field { isUnexported := sf.PkgPath != "" if sf.Anonymous { t := sf.Type - isPointer := t.Kind() == reflect.Ptr - if isPointer { + if t.Kind() == reflect.Ptr { t = t.Elem() } - isStruct := t.Kind() == reflect.Struct - if isUnexported && (!isStruct || isPointer) { - // Ignore embedded fields of unexported non-struct types - // or pointers to unexported struct types. - // - // The latter is forbidden because unmarshal is unable - // to assign a new struct to the unexported field. - // See https://golang.org/issue/21357 + if isUnexported && t.Kind() != reflect.Struct { + // Ignore embedded fields of unexported non-struct types. continue } // Do not ignore embedded fields of unexported struct types -- cgit v1.3