cr-report-app/internal/cache/gob.go

43 lines
823 B
Go
Raw Normal View History

2024-10-23 19:43:44 -04:00
package cache
import (
"bytes"
"context"
"encoding/gob"
"github.com/redis/go-redis/v9"
)
func StoreCacheGob[Data any](ctx context.Context, rdb *redis.Client, key string, data Data) error {
var buffer bytes.Buffer
encoder := gob.NewEncoder(&buffer)
// Serialize struct to Gob
err := encoder.Encode(data)
if err != nil {
return err
}
// Store data in Redis
return rdb.Set(ctx, key, buffer.Bytes(), 0).Err()
}
func GetCacheGob[Data any](ctx context.Context, rdb *redis.Client, key string) (Data, error) {
var data Data
binData, err := rdb.Get(ctx, key).Bytes()
if err != nil {
return data, err
}
buffer := bytes.NewBuffer(binData)
decoder := gob.NewDecoder(buffer)
// Deserialize Gob binary back to struct
err = decoder.Decode(&data)
if err != nil {
return data, err
}
return data, nil
}