file.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package repositories
  2. //go:generate mkdir -p mocks
  3. //go:generate rm -rf ./mocks/*_minimock.go
  4. //go:generate minimock -i git.dmitriygnatenko.ru/dima/homethings/internal/interfaces.FileRepository -o ./mocks/ -s "_minimock.go"
  5. import (
  6. "mime/multipart"
  7. "os"
  8. "git.dmitriygnatenko.ru/dima/homethings/internal/interfaces"
  9. "github.com/disintegration/imaging"
  10. "github.com/gofiber/fiber/v2"
  11. )
  12. const (
  13. uploadPath = "../../web/public"
  14. resizeWidth = 1000
  15. resizeHeight = 800
  16. )
  17. type fileRepository struct{}
  18. func InitFileRepository() interfaces.FileRepository {
  19. return fileRepository{}
  20. }
  21. func (r fileRepository) Save(fctx *fiber.Ctx, header *multipart.FileHeader, path string) error {
  22. fullPath := getFullPath(path)
  23. if err := fctx.SaveFile(header, fullPath); err != nil {
  24. return err
  25. }
  26. // Resize image
  27. src, err := imaging.Open(fullPath)
  28. if err != nil {
  29. return err
  30. }
  31. origHeight := src.Bounds().Size().Y
  32. origWidth := src.Bounds().Size().X
  33. var newHeight, newWidth int
  34. if origWidth > origHeight {
  35. newWidth = resizeWidth
  36. } else {
  37. newHeight = resizeHeight
  38. }
  39. dst := imaging.Resize(src, newWidth, newHeight, imaging.Lanczos)
  40. if err = imaging.Save(dst, fullPath); err != nil {
  41. return err
  42. }
  43. return nil
  44. }
  45. func (r fileRepository) Delete(path string) error {
  46. return os.RemoveAll(getFullPath(path))
  47. }
  48. func getFullPath(path string) string {
  49. return uploadPath + path
  50. }