Skip to content

Commit

Permalink
fix: register reFoldFn for types that derive from primitives (#46)
Browse files Browse the repository at this point in the history
This fixes the encoding of types that derive from a primitive type, such as net.IP which derives from []byte.

Relates: elastic/beats#37764
  • Loading branch information
pkoutsovasilis authored Jul 30, 2024
1 parent eef50e8 commit 878774d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions gotype/fold.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func NewIterator(vs structform.Visitor, opts ...FoldOption) (*Iterator, error) {
userReg = map[reflect.Type]reFoldFn{}
for typ, folder := range O.foldFns {
reg.set(typ, folder)
userReg[typ] = folder
}
}

Expand Down
43 changes: 43 additions & 0 deletions gotype/fold_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
gojson "encoding/json"
"errors"
"fmt"
"net"
"testing"
"time"

Expand Down Expand Up @@ -99,6 +100,18 @@ func TestUserFold(t *testing.T) {
return vs.OnInt64(t.Unix())
}

ip := net.IP([]byte{192, 168, 31, 1})
ipv6 := net.IP([]byte{
0x20, 0x01, 0x0d, 0xb8, // 2001:0db8
0x85, 0xa3, 0x00, 0x00, // 85a3:0000
0x00, 0x00, 0x8a, 0x2e, // 0000:8a2e
0x03, 0x70, 0x73, 0x34, // 0370:7334
})

foldIpString := func(t *net.IP, vs structform.ExtVisitor) error {
return vs.OnString(t.String())
}

tests := []struct {
in interface{}
fold interface{}
Expand Down Expand Up @@ -144,6 +157,36 @@ func TestUserFold(t *testing.T) {
fold: foldTsString,
want: sftest.Obj(1, structform.AnyType, "ts", sftest.StringRec{tsStr}),
},
{
in: ip,
fold: foldIpString,
want: sftest.Recording{sftest.StringRec{ip.String()}},
},
{
in: map[string]interface{}{"ip": ip},
fold: foldIpString,
want: sftest.Obj(1, structform.AnyType, "ip", sftest.StringRec{ip.String()}),
},
{
in: []net.IP{ip},
fold: foldIpString,
want: sftest.Arr(1, structform.AnyType, sftest.StringRec{ip.String()}),
},
{
in: ipv6,
fold: foldIpString,
want: sftest.Recording{sftest.StringRec{ipv6.String()}},
},
{
in: map[string]interface{}{"ip": ipv6},
fold: foldIpString,
want: sftest.Obj(1, structform.AnyType, "ip", sftest.StringRec{ipv6.String()}),
},
{
in: []net.IP{ipv6},
fold: foldIpString,
want: sftest.Arr(1, structform.AnyType, sftest.StringRec{ipv6.String()}),
},
}

for i, test := range tests {
Expand Down

0 comments on commit 878774d

Please sign in to comment.