I want to create a generic Redis interface for storing and getting values. I am beginner to Golang and redis. If there are any changes to be done to the code I would request you to help me.
package main
import (
"fmt"
"github.com/go-redis/redis"
)
func main() {
student := map[string]string{
"id": "st01",
"name": "namme1",
}
set("key1", student, 0)
get("key1")
}
func set(key string, value map[string]string, ttl int) bool {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
err := client.Set(key, value, 0).Err()
if err != nil {
fmt.Println(err)
return false
}
return true
}
func get(key string) bool {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
val, err := client.Get(key).Result()
if err != nil {
fmt.Println(err)
return false
}
fmt.Println(val)
return true
}
When i run this code i receive an error of "redis: can't marshal map[string]string (implement encoding.BinaryMarshaler)". I have tried using marshal but there was no use. I would request you to help me with this.
CodePudding user response:
The non-scalar type of go cannot be directly converted to the storage structure of redis, so the structure needs to be converted before storage
If you want to implement a general method, then the method should receive a type that can be stored directly, and the caller is responsible for converting the complex structure into a usable type, for example:
// ...
student := map[string]string{
"id": "st01",
"name": "namme1",
}
// Errors should be handled here
bs, _ := json.Marshal(student)
set("key1", bs, 0)
// ...
func set(key string, value interface{}, ttl int) bool {
// ...
}
A specific method can structure a specific structure, but the structure should implement the serializers encoding.MarshalBinary
and encoding.UnmarshalBinary
, for example:
type Student map[string]string
func (s Student) MarshalBinary() ([]byte, error) {
return json.Marshal(s)
}
func (s Student) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, &s)
}
// ...
student := Student{
"id": "st01",
"name": "namme1",
}
set("key1", student, 0)
// ...
func set(key string, value Student, ttl int) bool {
// ...
}