Closed jspc closed 2 years ago
To store a struct which contains more than just a simple key value pair, in your case key
-> []string
you need to write a custom encoder leveraging the RedisArg
and RedisScan
interfaces. Something like the following (not the most efficient code) will do the trick.
type Something struct {
Foo string
Bar string
Baz stringSlice
}
type stringSlice []string
func (ss stringSlice) RedisArg() interface{} {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
enc.Encode(ss)
return buf.Bytes()
}
func (ss *stringSlice) RedisScan(src interface{}) error {
v, ok := src.([]byte)
if !ok {
return fmt.Errorf("string slice: cannot convert from %T to %T", src, ss)
}
var buf bytes.Buffer
if _, err := buf.Write(v); err != nil {
return fmt.Errorf("string slice: write failed: %w", err)
}
dec := gob.NewDecoder(&buf)
if err := dec.Decode(ss); err != nil {
return fmt.Errorf("string slice: decode failed: %w", err)
}
return nil
}
Wonderful, thanks @stevenh
Hi there,
Given the following sample:
My program errors with:
Because while redigo can serialise a slice of strings to redis (which it turns to
"[blah blah blah]"
), I can't figure out how to get redigo to turn it back into something useful.Is there a way? Or does redigo need to fail on serialising in the first place, to avoid a situation where it can't read something back?