cache.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package cache
  2. import (
  3. "bytes"
  4. "context"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. log "github.com/sirupsen/logrus"
  10. )
  11. type Cache interface {
  12. Set(ctx context.Context, key string, value []byte) error
  13. Get(ctx context.Context, ey string) ([]byte, error)
  14. }
  15. type DirCache struct {
  16. path string
  17. }
  18. func NewDirCache(path string) *DirCache {
  19. return &DirCache{path}
  20. }
  21. func (d *DirCache) getCachePath(key string) string {
  22. return filepath.Join(d.path, key)
  23. }
  24. func (d *DirCache) Get(ctx context.Context, key string) ([]byte, error) {
  25. file, err := os.Open(d.getCachePath(key))
  26. if err != nil {
  27. if os.IsNotExist(err) {
  28. return nil, nil
  29. }
  30. return nil, err
  31. }
  32. defer file.Close()
  33. b := new(bytes.Buffer)
  34. if _, err = io.Copy(b, file); err != nil {
  35. log.Errorf("Error copying file to cache value: %v", err)
  36. return nil, err
  37. }
  38. return b.Bytes(), nil
  39. }
  40. func (d *DirCache) Set(ctx context.Context, key string, value []byte) error {
  41. log.Debugf("Setting cache item %v")
  42. if err := os.MkdirAll(d.path, 0777); err != nil {
  43. log.Errorf("Could not create cache dir %v: %v", d.path, err)
  44. return err
  45. }
  46. cacheTmpFile, err := ioutil.TempFile(d.path, key+".*")
  47. if err != nil {
  48. log.Errorf("Could not create cache file %v: %v", cacheTmpFile, err)
  49. return err
  50. }
  51. if _, err := io.Copy(cacheTmpFile, bytes.NewReader(value)); err != nil {
  52. log.Errorf("Could not write cache file %v: %v", cacheTmpFile, err)
  53. cacheTmpFile.Close()
  54. os.Remove(cacheTmpFile.Name())
  55. return err
  56. }
  57. if err = cacheTmpFile.Close(); err != nil {
  58. log.Errorf("Could not close cache file %v: %v", cacheTmpFile, err)
  59. os.Remove(cacheTmpFile.Name())
  60. return err
  61. }
  62. if err = os.Rename(cacheTmpFile.Name(), d.getCachePath(key)); err != nil {
  63. log.Errorf("Could not move cache file %v: %v", cacheTmpFile, err)
  64. os.Remove(cacheTmpFile.Name())
  65. return err
  66. }
  67. return nil
  68. }