1
|
|
|
//////////////////////////////////////////////////////////////////////////////// |
2
|
|
|
// Author: Nikita Koryabkin |
3
|
|
|
// Email: [email protected] |
4
|
|
|
// Telegram: https://t.me/Apologiz |
5
|
|
|
//////////////////////////////////////////////////////////////////////////////// |
6
|
|
|
|
7
|
|
|
package file |
8
|
|
|
|
9
|
|
|
import ( |
10
|
|
|
"errors" |
11
|
|
|
"github.com/spf13/afero" |
12
|
|
|
"io" |
13
|
|
|
"log" |
14
|
|
|
"os" |
15
|
|
|
"path/filepath" |
16
|
|
|
) |
17
|
|
|
|
18
|
|
|
const ( |
19
|
|
|
fileOptions = os.O_CREATE | os.O_APPEND | os.O_WRONLY |
20
|
|
|
filePermission = 0755 |
21
|
|
|
) |
22
|
|
|
|
23
|
|
|
// Strategy logging strategy in the File |
24
|
|
|
type Strategy struct { |
25
|
|
|
_ io.Writer |
26
|
|
|
File afero.File |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
var errCanNotCreateDirectory = errors.New("can't create directory") |
30
|
|
|
var errFileNotDefined = errors.New("file is not defined") |
31
|
|
|
var fs = afero.NewOsFs() |
32
|
|
|
|
33
|
|
|
// Get File write strategy |
34
|
|
|
func Get(filePath string) io.Writer { |
35
|
|
|
if addDirectory(filePath) == nil { |
36
|
|
|
file, err := openFile(filePath) |
37
|
|
|
if err == nil { |
38
|
|
|
return &Strategy{ |
39
|
|
|
File: file, |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
return &Strategy{} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
func (s *Strategy) Write(p []byte) (n int, err error) { |
47
|
|
|
if s.File != nil { |
48
|
|
|
return s.File.Write(p) |
49
|
|
|
} |
50
|
|
|
return 0, errFileNotDefined |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
func addDirectory(filePath string) error { |
54
|
|
|
if filePath == "" { |
55
|
|
|
return errCanNotCreateDirectory |
56
|
|
|
} |
57
|
|
|
dir, _ := filepath.Split(filePath) |
58
|
|
|
return createDirectoryIfNotExist(dir) |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
func createDirectoryIfNotExist(dirPath string) error { |
62
|
|
|
_, err := fs.Stat(dirPath) |
63
|
|
|
if os.IsNotExist(err) { |
64
|
|
|
return fs.MkdirAll(dirPath, filePermission) |
65
|
|
|
} |
66
|
|
|
return err |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
func openFile(filePath string) (afero.File, error) { |
70
|
|
|
if filePath == "" { |
71
|
|
|
log.Println(afero.ErrFileNotFound) |
72
|
|
|
return nil, afero.ErrFileNotFound |
73
|
|
|
} |
74
|
|
|
return fs.OpenFile(filePath, fileOptions, filePermission) |
75
|
|
|
} |
76
|
|
|
|