File tree Expand file tree Collapse file tree 2 files changed +24
-7
lines changed Expand file tree Collapse file tree 2 files changed +24
-7
lines changed Original file line number Diff line number Diff line change @@ -13,6 +13,11 @@ import (
13
13
// Map represents an ordered map of fields.
14
14
type Map []Field
15
15
16
+ // SlogValue implements Value.
17
+ func (m Map ) SlogValue () interface {} {
18
+ return ForceJSON (m )
19
+ }
20
+
16
21
var _ json.Marshaler = Map (nil )
17
22
18
23
// MarshalJSON implements json.Marshaler.
@@ -55,14 +60,14 @@ func (v jsonVal) MarshalJSON() ([]byte, error) {
55
60
return json .Marshal (v .v )
56
61
}
57
62
58
- func marshalArray ( a [] interface {} ) []byte {
63
+ func marshalList ( rv reflect. Value ) []byte {
59
64
b := & bytes.Buffer {}
60
65
b .WriteByte ('[' )
61
- for i , v := range a {
66
+ for i := 0 ; i < rv . Len (); i ++ {
62
67
b .WriteByte ('\n' )
63
- b .Write (encode (v ))
68
+ b .Write (encode (rv . Index ( i ). Interface () ))
64
69
65
- if i < len ( a )- 1 {
70
+ if i < rv . Len ( )- 1 {
66
71
b .WriteByte (',' )
67
72
}
68
73
}
@@ -75,13 +80,25 @@ func encode(v interface{}) []byte {
75
80
switch v := v .(type ) {
76
81
case Value :
77
82
return encode (v .SlogValue ())
78
- case []interface {}:
79
- return marshalArray (v )
80
83
case xerrors.Formatter :
81
84
return encode (errorChain (v ))
82
85
case error , fmt.Stringer :
83
86
return encode (fmt .Sprint (v ))
84
87
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
+
85
102
b , err := json .Marshal (v )
86
103
if err != nil {
87
104
return encode (M (
Original file line number Diff line number Diff line change @@ -93,7 +93,7 @@ func TestMap(t *testing.T) {
93
93
{
94
94
"msg": "failed to marshal to JSON",
95
95
"fun": "cdr.dev/slog.encode",
96
- "loc": "` + mapTestFile + `:88 "
96
+ "loc": "` + mapTestFile + `:105 "
97
97
},
98
98
"json: unsupported type: func(*testing.T, string) string"
99
99
],
You can’t perform that action at this time.
0 commit comments