Skip to content

Commit

Permalink
Add reflection encoder for lists
Browse files Browse the repository at this point in the history
  • Loading branch information
nhooyr committed Dec 10, 2019
1 parent 20ab272 commit b1f97d8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
29 changes: 23 additions & 6 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ import (
// Map represents an ordered map of fields.
type Map []Field

// SlogValue implements Value.
func (m Map) SlogValue() interface{} {
return ForceJSON(m)
}

var _ json.Marshaler = Map(nil)

// MarshalJSON implements json.Marshaler.
Expand Down Expand Up @@ -55,14 +60,14 @@ func (v jsonVal) MarshalJSON() ([]byte, error) {
return json.Marshal(v.v)
}

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

if i < len(a)-1 {
if i < rv.Len()-1 {
b.WriteByte(',')
}
}
Expand All @@ -75,13 +80,25 @@ func encode(v interface{}) []byte {
switch v := v.(type) {
case Value:
return encode(v.SlogValue())
case []interface{}:
return marshalArray(v)
case xerrors.Formatter:
return encode(errorChain(v))
case error, fmt.Stringer:
return encode(fmt.Sprint(v))
default:
rv := reflect.Indirect(reflect.ValueOf(v))
if rv.IsValid() {
switch rv.Type().Kind() {
case reflect.Slice:
if rv.IsNil() {
b, _ := json.Marshal(nil)
return b
}
fallthrough
case reflect.Array:
return marshalList(rv)
}
}

b, err := json.Marshal(v)
if err != nil {
return encode(M(
Expand Down
2 changes: 1 addition & 1 deletion map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func TestMap(t *testing.T) {
{
"msg": "failed to marshal to JSON",
"fun": "cdr.dev/slog.encode",
"loc": "`+mapTestFile+`:88"
"loc": "`+mapTestFile+`:105"
},
"json: unsupported type: func(*testing.T, string) string"
],
Expand Down

0 comments on commit b1f97d8

Please sign in to comment.