/
db.go
41 lines (36 loc) · 1018 Bytes
/
db.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
package fetcher
import (
"encoding/json"
"log"
"os"
"path/filepath"
"github.com/hi20160616/gears"
"github.com/hi20160616/ms-storm/configs"
"github.com/pkg/errors"
)
var dbfile = filepath.Join(configs.Data.RootPath, configs.Data.DBPath, "articles.json")
func storage(as []*Article) error {
defer log.Printf("[%s] Storage Done.", configs.Data.MS["storm"].Title)
log.Printf("[%s] Storage ...", configs.Data.MS["storm"].Title)
data, err := json.Marshal(as)
if err != nil {
return errors.WithMessagef(err, "[%s] storage marshal error:",
configs.Data.MS["storm"].Title)
}
gears.MakeDirAll(filepath.Join(configs.Data.RootPath, configs.Data.DBPath))
if err := os.WriteFile(dbfile, data, 0755); err != nil {
return errors.WithMessagef(err, "[%s] storage WriteFile error:",
configs.Data.MS["storm"].Title)
}
return nil
}
func load() (as []*Article, err error) {
data, err := os.ReadFile(dbfile)
if err != nil {
return
}
if err = json.Unmarshal(data, &as); err != nil {
return
}
return
}