/
media.go
89 lines (77 loc) · 2.42 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package service
import (
"context"
"github.com/gin-gonic/gin"
"github.com/jassue/gin-wire/app/compo"
"github.com/jassue/gin-wire/app/domain"
cErr "github.com/jassue/gin-wire/app/pkg/error"
"github.com/jassue/gin-wire/app/pkg/request"
"github.com/jassue/gin-wire/config"
"github.com/satori/go.uuid"
"go.uber.org/zap"
"path"
)
type MediaRepo interface {
Create(context.Context, *domain.Media) (*domain.Media, error)
FindByID(context.Context, uint64) (*domain.Media, error)
FindCacheByID(context.Context, uint64) (*domain.Media, error)
}
type MediaService struct {
conf *config.Configuration
log *zap.Logger
mRepo MediaRepo
storage *compo.Storage
}
// NewMediaService .
func NewMediaService(conf *config.Configuration, log *zap.Logger, mRepo MediaRepo, s *compo.Storage) *MediaService {
return &MediaService{conf: conf, log: log, mRepo: mRepo, storage: s}
}
func (s *MediaService) makeFaceDir(business string) string {
return s.conf.App.Env + "/" + business
}
func (s *MediaService) HashName(fileName string) string {
fileSuffix := path.Ext(fileName)
return uuid.NewV4().String() + fileSuffix
}
// SaveImage 保存图片(公共读)
func (s *MediaService) SaveImage(ctx *gin.Context, params *request.ImageUpload) (*domain.Media, error) {
file, err := params.Image.Open()
defer file.Close()
if err != nil {
return nil, cErr.BadRequest("上传失败")
}
disk, err := s.storage.GetDisk()
if err != nil {
return nil, cErr.BadRequest(s.storage.GetDefaultDiskType() + "disk not found")
}
localPrefix := ""
if s.storage.IsLocal() {
localPrefix = "public" + "/"
}
key := s.makeFaceDir(params.Business) + "/" + s.HashName(params.Image.Filename)
err = disk.Put(localPrefix + key, file, params.Image.Size)
if err != nil {
return nil, cErr.BadRequest("上传失败")
}
m, err := s.mRepo.Create(ctx, &domain.Media{
DiskType: s.storage.GetDefaultDiskType(),
SrcType: 1,
Src: key,
Url: disk.Url(key),
})
if err != nil {
return nil, cErr.BadRequest("上传失败")
}
return m, nil
}
func (s *MediaService) GetUrlById(ctx *gin.Context, id uint64) string {
if id == 0 {
return ""
}
m, err := s.mRepo.FindCacheByID(ctx, id)
if err != nil {
s.log.Error(err.Error())
return ""
}
return m.Url
}