local_storage.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package local
  2. import (
  3. "io/fs"
  4. "log"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/langgenius/dify-plugin-daemon/internal/oss"
  9. )
  10. type LocalStorage struct {
  11. root string
  12. }
  13. func NewLocalStorage(root string) oss.OSS {
  14. if err := os.MkdirAll(root, 0o755); err != nil {
  15. log.Panicf("Failed to create storage path: %s", err)
  16. }
  17. return &LocalStorage{root: root}
  18. }
  19. func (l *LocalStorage) Save(key string, data []byte) error {
  20. path := filepath.Join(l.root, key)
  21. filePath := filepath.Dir(path)
  22. if err := os.MkdirAll(filePath, 0o755); err != nil {
  23. return err
  24. }
  25. return os.WriteFile(path, data, 0o644)
  26. }
  27. func (l *LocalStorage) Load(key string) ([]byte, error) {
  28. path := filepath.Join(l.root, key)
  29. return os.ReadFile(path)
  30. }
  31. func (l *LocalStorage) Exists(key string) (bool, error) {
  32. path := filepath.Join(l.root, key)
  33. _, err := os.Stat(path)
  34. return err == nil, nil
  35. }
  36. func (l *LocalStorage) State(key string) (oss.OSSState, error) {
  37. path := filepath.Join(l.root, key)
  38. info, err := os.Stat(path)
  39. if err != nil {
  40. return oss.OSSState{}, err
  41. }
  42. return oss.OSSState{Size: info.Size(), LastModified: info.ModTime()}, nil
  43. }
  44. func (l *LocalStorage) List(prefix string) ([]oss.OSSPath, error) {
  45. prefix = filepath.Join(l.root, prefix)
  46. paths := make([]oss.OSSPath, 0)
  47. err := filepath.WalkDir(prefix, func(path string, d fs.DirEntry, err error) error {
  48. if err != nil {
  49. return err
  50. }
  51. // remove prefix
  52. path = strings.TrimPrefix(path, prefix)
  53. if path == "" {
  54. return nil
  55. }
  56. // remove leading slash
  57. path = strings.TrimPrefix(path, "/")
  58. paths = append(paths, oss.OSSPath{
  59. Path: path,
  60. IsDir: d.IsDir(),
  61. })
  62. return nil
  63. })
  64. if err != nil {
  65. return nil, err
  66. }
  67. return paths, nil
  68. }
  69. func (l *LocalStorage) Delete(key string) error {
  70. path := filepath.Join(l.root, key)
  71. return os.RemoveAll(path)
  72. }