-
Notifications
You must be signed in to change notification settings - Fork 0
/
yml.go
82 lines (76 loc) · 1.8 KB
/
yml.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
package config
import (
"errors"
"github.com/donetkit/contrib/utils/files"
"gopkg.in/yaml.v3"
"os"
"path"
)
type YMLConfig struct {
}
func (c *YMLConfig) LoadFullPath(filePath string, data interface{}) error {
if filePath == "" {
return errors.New("file path is empty")
}
file, err := os.Open(filePath)
if err != nil {
return err
}
defer func() { _ = file.Close() }()
if err = yaml.NewDecoder(file).Decode(data); err != nil {
return err
}
return nil
}
func (c *YMLConfig) SaveFullPath(filePath string, data interface{}) error {
if filePath == "" {
return errors.New("file path is empty")
}
file, err := os.Create(filePath)
if err != nil {
return err
}
defer func() { _ = file.Close() }()
if err := yaml.NewEncoder(file).Encode(data); err != nil {
return err
}
return nil
}
func (c *YMLConfig) Load(filePath, fileName string, data interface{}, save ...bool) error {
if filePath == "" {
return errors.New("file path is empty")
}
if fileName == "" {
return errors.New("file name is empty")
}
file, err := os.Open(path.Join(files.CurrentPath, filePath, fileName))
if err != nil {
if len(save) > 0 && save[0] {
c.Save(filePath, fileName, data)
}
return err
}
defer func() { _ = file.Close() }()
if err = yaml.NewDecoder(file).Decode(data); err != nil {
return err
}
return nil
}
func (c *YMLConfig) Save(filePath, fileName string, data interface{}) error {
if filePath == "" {
return errors.New("file path is empty")
}
if fileName == "" {
return errors.New("file name is empty")
}
files.IsNotExistMkDir(path.Join(files.CurrentPath, filePath))
file, err := os.Create(path.Join(files.CurrentPath, filePath, fileName))
if err != nil {
return err
}
defer func() { _ = file.Close() }()
if err := yaml.NewEncoder(file).Encode(data); err != nil {
return err
}
return nil
}