diff --git a/database/gdb/gdb_z_mysql_struct_test.go b/database/gdb/gdb_z_mysql_struct_test.go index 090a991a7..dbcf48d97 100644 --- a/database/gdb/gdb_z_mysql_struct_test.go +++ b/database/gdb/gdb_z_mysql_struct_test.go @@ -429,3 +429,26 @@ func Test_Model_Scan_UnmarshalValue(t *testing.T) { t.Assert(users[9].CreateTime.String(), CreateTime) }) } + +func Test_Model_Scan_Map(t *testing.T) { + table := createInitTable() + defer dropTable(table) + + gtest.C(t, func(t *gtest.T) { + var users []*User + err := db.Model(table).Order("id asc").Scan(&users) + t.AssertNil(err) + t.Assert(len(users), TableSize) + t.Assert(users[0].Id, 1) + t.Assert(users[0].Passport, "user_1") + t.Assert(users[0].Password, "") + t.Assert(users[0].Nickname, "name_1") + t.Assert(users[0].CreateTime.String(), CreateTime) + + t.Assert(users[9].Id, 10) + t.Assert(users[9].Passport, "user_10") + t.Assert(users[9].Password, "") + t.Assert(users[9].Nickname, "name_10") + t.Assert(users[9].CreateTime.String(), CreateTime) + }) +} diff --git a/util/gconv/gconv.go b/util/gconv/gconv.go index af74e7369..83d140625 100644 --- a/util/gconv/gconv.go +++ b/util/gconv/gconv.go @@ -13,6 +13,7 @@ import ( "fmt" "github.com/gogf/gf/internal/json" "github.com/gogf/gf/os/gtime" + "math" "reflect" "strconv" "strings" @@ -299,6 +300,32 @@ func Bytes(any interface{}) []byte { if f, ok := value.(apiBytes); ok { return f.Bytes() } + var ( + reflectValue = reflect.ValueOf(any) + reflectKind = reflectValue.Kind() + ) + for reflectKind == reflect.Ptr { + reflectValue = reflectValue.Elem() + reflectKind = reflectValue.Kind() + } + switch reflectKind { + case reflect.Array, reflect.Slice: + var ( + ok = true + bytes = make([]byte, reflectValue.Len()) + ) + for i, _ := range bytes { + int32Value := Int32(reflectValue.Index(i).Interface()) + if int32Value < 0 || int32Value > math.MaxUint8 { + ok = false + break + } + bytes[i] = byte(int32Value) + } + if ok { + return bytes + } + } return gbinary.Encode(any) } } @@ -308,7 +335,7 @@ func Rune(any interface{}) rune { if v, ok := any.(rune); ok { return v } - return rune(Int32(any)) + return Int32(any) } // Runes converts `any` to []rune. diff --git a/util/gconv/gconv_z_unit_slice_test.go b/util/gconv/gconv_z_unit_slice_test.go index 062b6fc17..c67f4bf3f 100644 --- a/util/gconv/gconv_z_unit_slice_test.go +++ b/util/gconv/gconv_z_unit_slice_test.go @@ -19,6 +19,8 @@ func Test_Slice(t *testing.T) { gtest.C(t, func(t *gtest.T) { value := 123.456 t.AssertEQ(gconv.Bytes("123"), []byte("123")) + t.AssertEQ(gconv.Bytes([]interface{}{1}), []byte{1}) + t.AssertEQ(gconv.Bytes([]interface{}{300}), []byte("[300]")) t.AssertEQ(gconv.Strings(value), []string{"123.456"}) t.AssertEQ(gconv.Ints(value), []int{123}) t.AssertEQ(gconv.Floats(value), []float64{123.456})