improve function Do for package gredis, adding auto marshal feature for arguments

This commit is contained in:
John
2020-05-18 19:18:53 +08:00
parent 7c2cff7d99
commit 89ccaa3915
3 changed files with 74 additions and 2 deletions

View File

@ -6,9 +6,44 @@
package gredis
import "github.com/gogf/gf/container/gvar"
import (
"encoding/json"
"github.com/gogf/gf/container/gvar"
"reflect"
)
// DoVar returns value from Do as gvar.Var.
// Do sends a command to the server and returns the received reply.
// It uses json.Marshal for struct/slice/map type values before committing them to redis.
func (c *Conn) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
var (
reflectValue reflect.Value
reflectKind reflect.Kind
)
for k, v := range args {
reflectValue = reflect.ValueOf(v)
reflectKind = reflectValue.Kind()
if reflectKind == reflect.Ptr {
reflectValue = reflectValue.Elem()
reflectKind = reflectValue.Kind()
}
switch reflectKind {
case
reflect.Struct,
reflect.Map,
reflect.Slice,
reflect.Array:
// Ignore slice type of: []byte.
if _, ok := v.([]byte); !ok {
if args[k], err = json.Marshal(v); err != nil {
return nil, err
}
}
}
}
return c.Conn.Do(commandName, args...)
}
// DoVar retrieves and returns the result from command as gvar.Var.
func (c *Conn) DoVar(command string, args ...interface{}) (*gvar.Var, error) {
v, err := c.Do(command, args...)
return gvar.New(v), err

View File

@ -281,3 +281,39 @@ func Test_HGetAll(t *testing.T) {
})
})
}
func Test_Auto_Marshal(t *testing.T) {
var (
err error
redis = gredis.New(config)
key = guid.S()
)
defer redis.Do("DEL", key)
type User struct {
Id int
Name string
}
gtest.C(t, func(t *gtest.T) {
user := &User{
Id: 10000,
Name: "john",
}
_, err = redis.Do("SET", key, user)
t.Assert(err, nil)
r, err := redis.DoVar("GET", key)
t.Assert(err, nil)
t.Assert(r.Map(), g.MapStrAny{
"Id": user.Id,
"Name": user.Name,
})
var user2 *User
t.Assert(r.Struct(&user2), nil)
t.Assert(user2.Id, user.Id)
t.Assert(user2.Name, user.Name)
})
}