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.

53 lines
1.4 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
  9. StoreExisting(bucketName string, objectName string, existingFilePath string) string
  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 {
  16. directoryPath := filepath.Join(sp.basePath, bucketName)
  17. sp.fileSystem.MkdirAll(directoryPath, os.ModePerm)
  18. filePath := filepath.Join(directoryPath, objectName)
  19. afero.WriteFile(sp.fileSystem, filePath, data, os.ModePerm)
  20. return filePath
  21. }
  22. func (sp FileSystemStorageProvider) StoreExisting(bucketName string, objectName string, existingFilePath string) string {
  23. bytesRead, _ := afero.ReadFile(sp.fileSystem, existingFilePath)
  24. return sp.StoreRaw(bucketName, objectName, bytesRead)
  25. }
  26. func GetFileSystemStorageProvider(basePath string) FileSystemStorageProvider {
  27. wd, _ := os.Getwd()
  28. return FileSystemStorageProvider{
  29. fileSystem: afero.NewBasePathFs(afero.NewOsFs(), filepath.Join(wd, "files")),
  30. basePath: basePath,
  31. }
  32. }
  33. // TODO: Move this out of this file
  34. func GetMemoryStorageProvider() FileSystemStorageProvider {
  35. return FileSystemStorageProvider{
  36. fileSystem: afero.NewBasePathFs(afero.NewMemMapFs(), "/"),
  37. basePath: "/tmp/foo/bar",
  38. }
  39. }