diskcache.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Package diskcache provides an implementation of httpcache.Cache that uses the diskv package
  2. // to supplement an in-memory map with persistent storage
  3. //
  4. package diskcache
  5. import (
  6. "bytes"
  7. "crypto/md5"
  8. "encoding/hex"
  9. "github.com/peterbourgon/diskv"
  10. "io"
  11. )
  12. // Cache is an implementation of httpcache.Cache that supplements the in-memory map with persistent storage
  13. type Cache struct {
  14. d *diskv.Diskv
  15. }
  16. // Get returns the response corresponding to key if present
  17. func (c *Cache) Get(key string) (resp []byte, ok bool) {
  18. key = keyToFilename(key)
  19. resp, err := c.d.Read(key)
  20. if err != nil {
  21. return []byte{}, false
  22. }
  23. return resp, true
  24. }
  25. // Set saves a response to the cache as key
  26. func (c *Cache) Set(key string, resp []byte) {
  27. key = keyToFilename(key)
  28. c.d.WriteStream(key, bytes.NewReader(resp), true)
  29. }
  30. // Delete removes the response with key from the cache
  31. func (c *Cache) Delete(key string) {
  32. key = keyToFilename(key)
  33. c.d.Erase(key)
  34. }
  35. func keyToFilename(key string) string {
  36. h := md5.New()
  37. io.WriteString(h, key)
  38. return hex.EncodeToString(h.Sum(nil))
  39. }
  40. // New returns a new Cache that will store files in basePath
  41. func New(basePath string) *Cache {
  42. return &Cache{
  43. d: diskv.New(diskv.Options{
  44. BasePath: basePath,
  45. CacheSizeMax: 100 * 1024 * 1024, // 100MB
  46. }),
  47. }
  48. }
  49. // NewWithDiskv returns a new Cache using the provided Diskv as underlying
  50. // storage.
  51. func NewWithDiskv(d *diskv.Diskv) *Cache {
  52. return &Cache{d}
  53. }