diskcache.go 717 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package cache
  2. import (
  3. "crypto/sha1"
  4. "encoding/hex"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. )
  9. type DiskCache struct {
  10. dir string
  11. }
  12. func NewDiskCache(dir string) (*DiskCache, error) {
  13. if err := os.MkdirAll(dir, 0o755); err != nil {
  14. return nil, fmt.Errorf("create cache dir: %w", err)
  15. }
  16. return &DiskCache{dir: dir}, nil
  17. }
  18. func (c *DiskCache) pathFor(key string) string {
  19. h := sha1.Sum([]byte(key))
  20. return filepath.Join(c.dir, hex.EncodeToString(h[:]))
  21. }
  22. func (c *DiskCache) Get(key string) ([]byte, bool) {
  23. b, err := os.ReadFile(c.pathFor(key))
  24. if err != nil {
  25. return nil, false
  26. }
  27. return b, true
  28. }
  29. func (c *DiskCache) Set(key string, data []byte) error {
  30. return os.WriteFile(c.pathFor(key), data, 0o644)
  31. }