-
Notifications
You must be signed in to change notification settings - Fork 0
/
local.go
118 lines (96 loc) · 2.57 KB
/
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package storage
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/konstantinfoerster/card-importer-go/internal/config"
"github.com/pkg/errors"
)
func NewLocalStorage(config config.Storage) (Storage, error) {
err := os.MkdirAll(config.Location, 0755)
if err != nil {
return nil, fmt.Errorf("failed to create storage dir %s %w", config.Location, err)
}
return &localStorage{
config: config,
}, nil
}
type localStorage struct {
config config.Storage
}
func (s *localStorage) fromBasePath(path ...string) string {
var escapeSafe []string
for _, p := range path {
if strings.TrimSpace(p) == ".." {
continue
}
escapeSafe = append(escapeSafe, p)
}
file := filepath.Join(s.config.Location, filepath.Join(escapeSafe...))
file = filepath.Clean(file)
return file
}
func (s *localStorage) Store(r io.Reader, path ...string) (*StoredFile, error) {
filePath := s.fromBasePath(path...)
if len(path) > 1 {
err := os.MkdirAll(filepath.Dir(filePath), 0755)
if err != nil {
return nil, fmt.Errorf("failed to create sub dirs for %s %w", filePath, err)
}
}
flags := os.O_RDWR | os.O_CREATE
if s.config.Mode == config.REPLACE {
flags |= os.O_TRUNC // truncate existing file
} else {
flags |= os.O_EXCL // file must not exist
}
target, err := os.OpenFile(filePath, flags, 0666)
if err != nil {
return nil, fmt.Errorf("failed to create empty file %s with mode %s %w", filePath, s.config.Mode, err)
}
defer func(toClose *os.File) {
cErr := toClose.Close()
if cErr != nil {
// report close errors
if err == nil {
err = cErr
} else {
err = errors.Wrap(err, cErr.Error())
}
}
}(target)
_, err = io.Copy(target, r)
if err != nil {
return nil, fmt.Errorf("failed to copy file %w", err)
}
err = target.Sync()
if err != nil {
return nil, fmt.Errorf("failed to sync file %w", err)
}
return &StoredFile{
AbsolutePath: filePath,
Path: s.removeBasePath(filePath),
}, err
}
func (s *localStorage) removeBasePath(path string) string {
noBasePath := strings.TrimPrefix(path, s.config.Location)
noBasePath = strings.TrimPrefix(noBasePath, "/")
return noBasePath
}
func (s *localStorage) Load(path ...string) (io.ReadCloser, error) {
filePath := s.fromBasePath(path...)
info, err := os.Stat(filePath)
if err != nil {
return nil, fmt.Errorf("failed to get file info %s %w", filePath, err)
}
if info.IsDir() {
return nil, fmt.Errorf("loading a directory is not supported")
}
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("failed to open file %s %w", filePath, err)
}
return file, nil
}