-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
131 lines (106 loc) · 2.49 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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
package files
/* *
* Copyright (c) 2023, @jhekau <mr.evgeny.u@gmail.com>
* 10 March 2023
*/
import (
"io"
"os"
"path/filepath"
"time"
err_ "github.com/jhekau/favicon/internal/pkg/err"
logger_ "github.com/jhekau/favicon/pkg/core/models/logger"
storage_ "github.com/jhekau/favicon/pkg/core/models/storage"
)
const (
logP = `/internal/storage/files/file.go`
logS01 = `S01: can't get path`
logS02 = `S02: failed open file`
logS03 = `S03: os stat source image`
logS04 = `S04: save thumb image is a folder`
logS05 = `S05: failed open file`
logS06 = `S06: os stat source image`
logS07 = `S07: can't get path`
logS08 = `S08: can't create dir`
)
// for test
var (
osOpen = os.Open
osStat = os.Stat
)
var DirIconsDefault = `icons` // default
// storage object
type file struct{
l logger_.Logger
key string
dir string
}
func (s *file) Reader() (io.ReadSeekCloser, error) {
fpath, err := filepath.Abs(filepath.Join(s.dir, s.key))
if err != nil {
return nil, err_.Err(s.l, logP, logS01, err)
}
f, err := osOpen(fpath)
if err != nil {
return nil, err_.Err(s.l, logP, logS02, err)
}
return f, nil
}
func (s *file) Writer() (io.WriteCloser, error){
fpath, err := filepath.Abs(filepath.Join(s.dir, s.key))
if err != nil {
return nil, err_.Err(s.l, logP, logS07, err)
}
err = os.MkdirAll(filepath.Dir(fpath), 0775)
if err != nil {
return nil, err_.Err(s.l, logP, logS08, err)
}
f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return nil, err_.Err(s.l, logP, logS05, err)
}
return f, nil
}
func (s *file) IsExists() ( bool, error ) {
if s == nil {
return false, nil
}
if f, err := osStat( filepath.Join(s.dir, s.key) ); err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err_.Err(s.l, logP, logS03, err)
} else if f.IsDir() {
return false, err_.Err(s.l, logP, logS04)
}
return true, nil
}
func (s *file) Key() storage_.StorageKey {
return storage_.StorageKey(s.key)
}
func (s *file) ModTime() time.Time {
if s.key == `` {
return time.Time{}
}
st, err := osStat(filepath.Join(s.dir, s.key))
if err != nil {
err_.Err(s.l, logP, logS06, err)
return time.Time{}
}
return st.ModTime()
}
// TODO ?
// func (s *File) Delete()....
// storage
type Storage struct{
Dir string
L logger_.Logger
}
// получаем интерфейсы на объект в storage
func (s Storage) NewObject( key any ) (storage_.StorageOBJ, error) {
return &file{
l: s.L,
key: key.(string),
dir: s.Dir,
}, nil
}