-
Notifications
You must be signed in to change notification settings - Fork 0
/
archives.go
98 lines (80 loc) · 2.34 KB
/
archives.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package models
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"mime/multipart"
"os"
"github.com/upb-code-labs/static-files-microservice/config"
"github.com/upb-code-labs/static-files-microservice/utils"
)
func SaveArchive(directory string, uuid string, file multipart.File) (err error) {
// Create an empty file
volumePath := config.GetEnvironment().ArchivesVolumePath
path := fmt.Sprintf("%s/%s/%s.zip", volumePath, directory, uuid)
emptyFile, err := os.Create(path)
if err != nil {
log.Println(err)
return errors.New("error while creating the file")
}
// Reset the file pointer
_, err = file.Seek(0, 0)
if err != nil {
log.Println(err)
return errors.New("error while resetting the file pointer")
}
// Read the file bytes
buffer := bytes.NewBuffer(nil)
if _, err := io.Copy(buffer, file); err != nil {
log.Println(err)
return errors.New("error while reading the file")
}
// Write the file bytes
if _, err := emptyFile.Write(buffer.Bytes()); err != nil {
log.Println(err)
return errors.New("error while writing the file")
}
return nil
}
func DoesFileExists(directory string, uuid string) bool {
volumePath := config.GetEnvironment().ArchivesVolumePath
path := fmt.Sprintf("%s/%s/", volumePath, directory)
file := fmt.Sprintf("%s.zip", uuid)
return utils.DoesFileExists(path, file)
}
func GetArchive(directory string, uuid string) (fileBytes []byte, err error) {
// Get the file path
volumePath := config.GetEnvironment().ArchivesVolumePath
path := fmt.Sprintf("%s/%s/", volumePath, directory)
file := fmt.Sprintf("%s.zip", uuid)
return utils.ReadFile(path, file)
}
func OverwriteArchive(directory string, uuid string, file multipart.File) (err error) {
// Delete the file
err = DeleteArchive(directory, uuid)
if err != nil {
log.Println(err)
return errors.New("error while deleting the file")
}
// Save the file
err = SaveArchive(directory, uuid, file)
if err != nil {
log.Println(err)
return errors.New("error while saving the file")
}
return nil
}
func DeleteArchive(directory string, uuid string) (err error) {
// Get the file path
volumePath := config.GetEnvironment().ArchivesVolumePath
path := fmt.Sprintf("%s/%s/%s.zip", volumePath, directory, uuid)
// Delete the file
err = os.Remove(path)
if err != nil {
log.Println(err)
return errors.New("error while deleting the file")
}
return nil
}