Micro-service for file storage and processing written in Go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.5 KiB

  1. package storage
  2. import (
  3. "os"
  4. "path/filepath"
  5. "github.com/spf13/afero"
  6. )
  7. type IStorageProvider interface {
  8. StoreRaw(bucketName string, objectName string, data []byte) (string, error)
  9. StoreExisting(bucketName string, objectName string, existingFilePath string) (string, error)
  10. }
  11. type FileSystemStorageProvider struct {
  12. fileSystem afero.Fs
  13. basePath string
  14. }
  15. func (sp FileSystemStorageProvider) StoreRaw(bucketName string, objectName string, data []byte) (string, error) {
  16. directoryPath := filepath.Join(sp.basePath, bucketName)
  17. if err := sp.fileSystem.MkdirAll(directoryPath, os.ModePerm); err != nil {
  18. return "", err
  19. }
  20. filePath := filepath.Join(directoryPath, objectName)
  21. if err := afero.WriteFile(sp.fileSystem, filePath, data, os.ModePerm); err != nil {
  22. return "", err
  23. }
  24. return filePath, nil
  25. }
  26. func (sp FileSystemStorageProvider) StoreExisting(bucketName string, objectName string, existingFilePath string) (string, error) {
  27. bytesRead, _ := afero.ReadFile(sp.fileSystem, existingFilePath)
  28. return sp.StoreRaw(bucketName, objectName, bytesRead)
  29. }
  30. func GetFileSystemStorageProvider(basePath string) FileSystemStorageProvider {
  31. wd, _ := os.Getwd()
  32. return FileSystemStorageProvider{
  33. fileSystem: afero.NewBasePathFs(afero.NewOsFs(), filepath.Join(wd, "files")),
  34. basePath: basePath,
  35. }
  36. }
  37. // TODO: Move this out of this file
  38. func GetMemoryStorageProvider() FileSystemStorageProvider {
  39. return FileSystemStorageProvider{
  40. fileSystem: afero.NewBasePathFs(afero.NewMemMapFs(), "/"),
  41. basePath: "/tmp/foo/bar",
  42. }
  43. }