Skip to content

Commit b1f97d8

Browse files
committed
Add reflection encoder for lists
1 parent 20ab272 commit b1f97d8

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

map.go

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ import (
1313
// Map represents an ordered map of fields.
1414
type Map []Field
1515

16+
// SlogValue implements Value.
17+
func (m Map) SlogValue() interface{} {
18+
return ForceJSON(m)
19+
}
20+
1621
var _ json.Marshaler = Map(nil)
1722

1823
// MarshalJSON implements json.Marshaler.
@@ -55,14 +60,14 @@ func (v jsonVal) MarshalJSON() ([]byte, error) {
5560
return json.Marshal(v.v)
5661
}
5762

58-
func marshalArray(a []interface{}) []byte {
63+
func marshalList(rv reflect.Value) []byte {
5964
b := &bytes.Buffer{}
6065
b.WriteByte('[')
61-
for i, v := range a {
66+
for i := 0; i < rv.Len(); i++ {
6267
b.WriteByte('\n')
63-
b.Write(encode(v))
68+
b.Write(encode(rv.Index(i).Interface()))
6469

65-
if i < len(a)-1 {
70+
if i < rv.Len()-1 {
6671
b.WriteByte(',')
6772
}
6873
}
@@ -75,13 +80,25 @@ func encode(v interface{}) []byte {
7580
switch v := v.(type) {
7681
case Value:
7782
return encode(v.SlogValue())
78-
case []interface{}:
79-
return marshalArray(v)
8083
case xerrors.Formatter:
8184
return encode(errorChain(v))
8285
case error, fmt.Stringer:
8386
return encode(fmt.Sprint(v))
8487
default:
88+
rv := reflect.Indirect(reflect.ValueOf(v))
89+
if rv.IsValid() {
90+
switch rv.Type().Kind() {
91+
case reflect.Slice:
92+
if rv.IsNil() {
93+
b, _ := json.Marshal(nil)
94+
return b
95+
}
96+
fallthrough
97+
case reflect.Array:
98+
return marshalList(rv)
99+
}
100+
}
101+
85102
b, err := json.Marshal(v)
86103
if err != nil {
87104
return encode(M(

map_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ func TestMap(t *testing.T) {
9393
{
9494
"msg": "failed to marshal to JSON",
9595
"fun": "cdr.dev/slog.encode",
96-
"loc": "`+mapTestFile+`:88"
96+
"loc": "`+mapTestFile+`:105"
9797
},
9898
"json: unsupported type: func(*testing.T, string) string"
9999
],

0 commit comments

Comments
 (0)