chore: handle NaN values in encoder (#9998)

This commit is contained in:
andig 2023-09-22 08:47:58 +02:00 • committed by GitHub
parent 6331fd57b1
commit 34afaef175
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 1 deletions

View file

@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"math"
"reflect"
"strings"
"time"
@ -39,8 +40,33 @@ func encode(v interface{}) (string, error) {
return s, nil
}
func encodeSlice(v interface{}) (string, error) {
rv := reflect.ValueOf(v)
res := make([]string, rv.Len())
for i := 0; i < rv.Len(); i++ {
var err error
if res[i], err = encode(rv.Index(i).Interface()); err != nil {
return "", err
}
}
return fmt.Sprintf("[%s]", strings.Join(res, ",")), nil
}
func kv(p util.Param) string {
val, err := encode(p.Val)
var (
val string
err error
)
// unwrap slices
if p.Val != nil && reflect.TypeOf(p.Val).Kind() == reflect.Slice {
val, err = encodeSlice(p.Val)
} else {
val, err = encode(p.Val)
}
if err != nil {
panic(err)
}

View file

@ -31,3 +31,20 @@ func TestEncode(t *testing.T) {
assert.Equal(t, tc.out, out)
}
}
func TestEncodeSlice(t *testing.T) {
tc := []struct {
in interface{}
out string
}{
{[]string{"a", "b"}, `["a","b"]`},
{[2]int64{1, 2}, `[1,2]`},
{[]float64{1, math.NaN()}, `[1,null]`},
}
for _, tc := range tc {
out, err := encodeSlice(tc.in)
assert.NoError(t, err)
assert.Equal(t, tc.out, out)
}
}