...

Source file src/github.com/gregjones/httpcache/leveldbcache/leveldbcache.go

Documentation: github.com/gregjones/httpcache/leveldbcache

     1  // Package leveldbcache provides an implementation of httpcache.Cache that
     2  // uses github.com/syndtr/goleveldb/leveldb
     3  package leveldbcache
     4  
     5  import (
     6  	"github.com/syndtr/goleveldb/leveldb"
     7  )
     8  
     9  // Cache is an implementation of httpcache.Cache with leveldb storage
    10  type Cache struct {
    11  	db *leveldb.DB
    12  }
    13  
    14  // Get returns the response corresponding to key if present
    15  func (c *Cache) Get(key string) (resp []byte, ok bool) {
    16  	var err error
    17  	resp, err = c.db.Get([]byte(key), nil)
    18  	if err != nil {
    19  		return []byte{}, false
    20  	}
    21  	return resp, true
    22  }
    23  
    24  // Set saves a response to the cache as key
    25  func (c *Cache) Set(key string, resp []byte) {
    26  	c.db.Put([]byte(key), resp, nil)
    27  }
    28  
    29  // Delete removes the response with key from the cache
    30  func (c *Cache) Delete(key string) {
    31  	c.db.Delete([]byte(key), nil)
    32  }
    33  
    34  // New returns a new Cache that will store leveldb in path
    35  func New(path string) (*Cache, error) {
    36  	cache := &Cache{}
    37  
    38  	var err error
    39  	cache.db, err = leveldb.OpenFile(path, nil)
    40  
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  	return cache, nil
    45  }
    46  
    47  // NewWithDB returns a new Cache using the provided leveldb as underlying
    48  // storage.
    49  func NewWithDB(db *leveldb.DB) *Cache {
    50  	return &Cache{db}
    51  }
    52  

View as plain text