/
file.go
60 lines (49 loc) · 1.16 KB
/
file.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
package server
import (
"io"
"io/ioutil"
"log"
"mime/multipart"
"os"
"strings"
)
// File used to handle file path and file operation.
// We use interface so we can swap it to other file storage easily
type File interface {
GetFile(src string) ([]byte, error)
Upload(file *multipart.FileHeader, destPath string) error
}
type LocalFile struct {
}
func (f LocalFile) GetFile(srcPath string) ([]byte, error) {
file, err := ioutil.ReadFile(srcPath)
return file, err
}
// Upload saves uploaded file to the destined path
func (f LocalFile) Upload(file *multipart.FileHeader, destPath string) error {
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
// Create all directory if not exists
s := strings.Split(destPath, "/")
s = s[:len(s)-1]
sJoin := strings.Join(s, "/")
if _, err := os.Stat(sJoin); os.IsNotExist(err) {
log.Print("Upload folder is missing. Creating folder...")
os.MkdirAll(sJoin, os.ModePerm)
log.Print("Folder created in ", sJoin)
}
// Destination
dst, err := os.Create(destPath)
if err != nil {
return err
}
defer dst.Close()
// Copy
if _, err = io.Copy(dst, src); err != nil {
return err
}
return nil
}