I have a following piece of code in which I am trying to add an array to a redis set but it is giving me an error.
package main
import (
"encoding/json"
"fmt"
"github.com/go-redis/redis"
)
type Info struct {
Name string
Age int
}
func (i *Info) MarshalBinary() ([]byte, error) {
return json.Marshal(i)
}
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
ReadTimeout: -1,
})
pong, err := client.Ping().Result()
fmt.Print(pong, err)
infos := [2]Info{
{
Name: "tom",
Age: 20,
},
{
Name: "john doe",
Age: 30,
},
}
pipe := client.Pipeline()
pipe.Del("testing_set")
// also tried this
// pipe.SAdd("testing_set", []interface{}{infos[0], infos[1]})
pipe.SAdd("testing_set", infos)
_, err = pipe.Exec()
fmt.Println(err)
}
I get the error can't marshal [2]main.Info (implement encoding.BinaryMarshaler)
I have also tried to convert each info to []byte
and pass in the [][]byte...
to SAdd
but same error. How would I do this idomatically?
2
Answers
MarshalBinary() method should be as below
note: Info instead of *Info
Redis is based on key-value pairs, and key-values are all strings and other string-based data structures. Therefore, if you want to put some data into redis, you should make these data strings.
I think you should implement this interface like code below to make go-redis able to stringify your type:
In this way, you implement this method and go-redis will call this method to stringify(or marshal) your data.