/
media.go
66 lines (52 loc) · 1.23 KB
/
media.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
package media
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/google/uuid"
"github.com/DmitryVesenniy/go-rest-framework/common"
)
type MediaServise struct {
MediaPath string
}
type MediaEntity struct {
FileName string
Path string
}
func (mediaEntity *MediaEntity) Url() string {
return filepath.Join(mediaEntity.Path, mediaEntity.FileName)
}
func (media *MediaServise) SaveMediaFile(fileName string, content []byte, userPath string) (MediaEntity, error) {
result := MediaEntity{
FileName: fileName,
Path: media.MediaPath,
}
if userPath != "" {
filePath := filepath.Join(media.MediaPath, userPath)
result.Path = filePath
}
if isExists, _ := common.Exists(result.Url()); isExists {
uid := uuid.New()
fileNameSplitted := strings.Split(fileName, ".")
fileNameSplitted[0] = fmt.Sprintf("%s_%s", fileNameSplitted[0], uid)
result.FileName = strings.Join(fileNameSplitted, ".")
}
f, err := os.Create(result.Url())
if err != nil {
return result, err
}
defer f.Close()
_, err = f.Write(content)
if err != nil {
return result, err
}
err = f.Sync()
if err != nil {
return result, err
}
return result, nil
}
func (media *MediaServise) DeleteMediaFile(url string) error {
return os.Remove(url)
}