golang.org/x/playground@v0.0.0-20230418134305-14ebe15bcd59/cache.go (about)

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"bytes"
     9  	"encoding/gob"
    10  
    11  	"github.com/bradfitz/gomemcache/memcache"
    12  )
    13  
    14  // responseCache is a common interface for cache implementations.
    15  type responseCache interface {
    16  	// Set sets the value for a key.
    17  	Set(key string, v interface{}) error
    18  	// Get sets v to the value stored for a key.
    19  	Get(key string, v interface{}) error
    20  }
    21  
    22  // gobCache stores and retrieves values using a memcache client using the gob
    23  // encoding package. It does not currently allow for expiration of items.
    24  // With a nil gobCache, Set is a no-op and Get will always return memcache.ErrCacheMiss.
    25  type gobCache struct {
    26  	client *memcache.Client
    27  }
    28  
    29  func newGobCache(addr string) *gobCache {
    30  	return &gobCache{memcache.New(addr)}
    31  }
    32  
    33  func (c *gobCache) Set(key string, v interface{}) error {
    34  	if c == nil {
    35  		return nil
    36  	}
    37  	var buf bytes.Buffer
    38  	if err := gob.NewEncoder(&buf).Encode(v); err != nil {
    39  		return err
    40  	}
    41  	return c.client.Set(&memcache.Item{Key: key, Value: buf.Bytes()})
    42  }
    43  
    44  func (c *gobCache) Get(key string, v interface{}) error {
    45  	if c == nil {
    46  		return memcache.ErrCacheMiss
    47  	}
    48  	item, err := c.client.Get(key)
    49  	if err != nil {
    50  		return err
    51  	}
    52  	return gob.NewDecoder(bytes.NewBuffer(item.Value)).Decode(v)
    53  }