From 61d93d1cc9fbc0904a8a996ade3878f6b8c3a845 Mon Sep 17 00:00:00 2001 From: Matthew Date: Wed, 23 Oct 2024 19:43:44 -0400 Subject: [PATCH] functions for manipulating gobs --- internal/cache/gob.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 internal/cache/gob.go diff --git a/internal/cache/gob.go b/internal/cache/gob.go new file mode 100644 index 0000000..220e860 --- /dev/null +++ b/internal/cache/gob.go @@ -0,0 +1,42 @@ +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 +}