github.com/dimeko/sapi@v0.0.0-20231115204413-952501e4268a/store/cache/store.go (about)

     1  package cache
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"hash/fnv"
     7  	"log"
     8  	"os"
     9  	"path/filepath"
    10  
    11  	"github.com/bradfitz/gomemcache/memcache"
    12  	"github.com/joho/godotenv"
    13  )
    14  
    15  type Cache struct {
    16  	mc *memcache.Client
    17  }
    18  
    19  func env() map[string]string {
    20  	err := godotenv.Load(filepath.Join("./", ".env"))
    21  	if err != nil {
    22  		panic("Cannot find .env file")
    23  	}
    24  	return map[string]string{
    25  		"host": os.Getenv("MEMCACHED_HOST"),
    26  		"port": os.Getenv("MEMCACHED_PORT"),
    27  	}
    28  }
    29  
    30  func hash(s string) string {
    31  	h := fnv.New64a()
    32  	h.Write([]byte(s))
    33  	return fmt.Sprint(h.Sum64())
    34  }
    35  
    36  func New() *Cache {
    37  	connectionString := env()["host"] + ":" + env()["port"]
    38  	log.Println("Connecting to cache:", connectionString)
    39  	mc := memcache.New(connectionString)
    40  
    41  	cache := &Cache{
    42  		mc: mc,
    43  	}
    44  
    45  	return cache
    46  }
    47  
    48  func (c *Cache) Set(key string, payload interface{}) (string, error) {
    49  	cacheKey := hash(key)
    50  	cacheValue, err := json.Marshal(payload)
    51  
    52  	if err != nil {
    53  		return "", err
    54  	}
    55  	c.mc.Set(&memcache.Item{Key: cacheKey, Value: cacheValue})
    56  
    57  	return cacheKey, nil
    58  }
    59  
    60  func (c *Cache) Get(key string) (*memcache.Item, error) {
    61  	cacheKey := hash(key)
    62  	item, err := c.mc.Get(cacheKey)
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  
    67  	return item, nil
    68  }
    69  
    70  func (c *Cache) Remove(key string) error {
    71  	cacheKey := hash(key)
    72  	err := c.mc.Delete(cacheKey)
    73  	if err != nil {
    74  		return err
    75  	}
    76  	return nil
    77  }