Skip to content

Commit 7487181

Browse files
authored
Merge pull request #12 from t00ts/master
Prevent panic on `struct` types containing unexported fields
2 parents fb1b1d9 + f928137 commit 7487181

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

binary.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ func (b *Encoder) Encode(v interface{}) (err error) {
104104
l := rv.NumField()
105105
n := 0
106106
for i := 0; i < l; i++ {
107-
if v := rv.Field(i); t.Field(i).Name != "_" {
107+
if v := rv.Field(i); t.Field(i).Name != "_" && t.Field(i).IsExported() {
108108
if err = b.Encode(v.Interface()); err != nil {
109109
return
110110
}

binary_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,36 @@ func TestMarshalNonPointer(t *testing.T) {
276276
}
277277
}
278278

279+
func TestStructWithPrivateFields(t *testing.T) {
280+
281+
type S struct {
282+
Public int
283+
AnotherPublic int
284+
private int
285+
}
286+
287+
s := S{
288+
Public: 123,
289+
AnotherPublic: 456,
290+
private: -555,
291+
}
292+
293+
assert.NotPanics(t, func() {
294+
295+
data, err := Marshal(s)
296+
assert.NoError(t, err)
297+
298+
var res S
299+
if err := Unmarshal(data, &res); err != nil {
300+
t.Fatal(err)
301+
}
302+
assert.Equal(t, s.Public, res.Public)
303+
assert.Equal(t, s.AnotherPublic, res.AnotherPublic)
304+
305+
})
306+
307+
}
308+
279309
func BenchmarkEncodeStructI1(b *testing.B) {
280310
type Struct struct {
281311
S struct {

0 commit comments

Comments
 (0)