/
filebackend.go
89 lines (75 loc) 路 1.64 KB
/
filebackend.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
package cfg
import (
"encoding/json"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v2"
)
type Format int
const (
FormatJSON Format = iota
FormatYAML = iota
)
// FileBackend implements a filesystem backend for the configuration
type FileBackend struct {
format Format
}
// NewFileBackend returns a FileBackend that handles loading and
// saving files from the local filesytem.
func NewFileBackend() *FileBackend {
return &FileBackend{format: FormatJSON}
}
// Load loads chains from config
func (fs *FileBackend) Load(u *url.URL) (*Config, error) {
var config Config
// detect file format by extension
if strings.HasSuffix(u.Path, ".yaml") {
fs.format = FormatYAML
} else if strings.HasSuffix(u.Path, ".yml") {
fs.format = FormatYAML
} else {
fs.format = FormatJSON
}
if !exist(u.Path) {
return &Config{url: u}, nil
}
content, err := ioutil.ReadFile(u.Path)
if err != nil {
return &config, err
}
if fs.format == FormatYAML {
err = yaml.Unmarshal(content, &config)
} else {
err = json.Unmarshal(content, &config)
}
if err != nil {
return nil, err
}
config.backend = fs
config.url = u
return &config, nil
}
// Save saves chains to config
func (fs *FileBackend) Save(config *Config) error {
cfgDir := filepath.Dir(config.URL().Path)
if !exist(cfgDir) {
err := os.MkdirAll(cfgDir, 0755)
if err != nil {
return err
}
}
var content []byte
var err error
if fs.format == FormatYAML {
content, err = yaml.Marshal(config)
} else {
content, err = json.MarshalIndent(config, "", " ")
}
if err != nil {
return err
}
return ioutil.WriteFile(config.URL().Path, content, 0644)
}