-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprovider.local.go
95 lines (79 loc) · 1.71 KB
/
provider.local.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
package provider
import (
"context"
"io"
"mime/multipart"
"os"
"path"
"sync"
"github.com/diki-haryadi/govega/config"
"github.com/diki-haryadi/govega/log"
)
var copyBufPool = sync.Pool{
New: func() interface{} {
return make([]byte, 4096)
},
}
type Local struct {
Filepath string `json:"filepath" mapstructure:"filepath"`
}
func NewLocalStorage(conf config.Getter) (StorageProvider, error) {
var local *Local
if err := conf.Unmarshal(&local); err != nil {
return nil, err
}
err := os.MkdirAll(local.Filepath, os.ModePerm)
if err != nil {
log.WithError(err)
return nil, err
}
return local, nil
}
func (l *Local) Get(ctx context.Context, fullpath string) (io.Reader, error) {
var (
data *os.File
err error
)
fn := path.Join(l.Filepath, fullpath)
data, err = os.Open(fn)
if err != nil {
return nil, err
}
// defer data.Close()
return data, nil
}
func (l *Local) Put(ctx context.Context, fullpath string, f io.Reader) (err error) {
var ff *os.File
fn := path.Join(l.Filepath, fullpath)
switch file := f.(type) {
case *os.File:
// If renaming fails we try the normal copying method.
// Renaming could fail if the files are on different devices.
ff = file
if os.Rename(ff.Name(), fn) == nil {
return nil
}
case multipart.File:
// when f cannot cast to *os.File and f is multipart.sectionReadCloser
file.Seek(0, 0)
}
ff, err = os.Create(fn)
if err != nil {
return err
}
defer func() {
e := ff.Close()
if err == nil {
err = e
}
}()
_, err = copyZeroAlloc(ff, f)
return err
}
func copyZeroAlloc(w io.Writer, r io.Reader) (int64, error) {
vbuf := copyBufPool.Get()
buf := vbuf.([]byte)
n, err := io.CopyBuffer(w, r, buf)
copyBufPool.Put(vbuf)
return n, err
}