functions for manipulating gobs

master
Matthew 2024-10-23 19:43:44 -04:00
parent 50072202ca
commit 61d93d1cc9
Signed by: matthew
SSH Key Fingerprint: SHA256:piIXekA9q1p0ZGi4ogFbNY1embip5Ytbi3v8AZ8UYq4
1 changed files with 42 additions and 0 deletions

42
internal/cache/gob.go vendored Normal file
View File

@ -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
}