-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfileDB.go
More file actions
76 lines (67 loc) · 1.72 KB
/
fileDB.go
File metadata and controls
76 lines (67 loc) · 1.72 KB
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
package valuator
import (
"bytes"
"errors"
"io"
"io/ioutil"
"log"
"os"
)
/*
FileDB is an internally supported implementation of the Database interface.
This be used by applications that want to simply uses text files to save the
output received from the valuator to store information for later use.
The file path will be provided by the app and the name of the files will
be detrmined by the ticker that is being queried.
*/
type fileDB struct {
path string
writer map[string]*os.File
}
func newFileDB(url string) *fileDB {
return &fileDB{
path: url,
writer: make(map[string]*os.File),
}
}
func (f *fileDB) generateFilePath(filename string) string {
return f.path + filename + ".json"
}
func (f *fileDB) Open() error {
_, err := os.Stat(f.path)
return err
}
func (f *fileDB) Close() {
for _, writer := range f.writer {
writer.Close()
}
}
func (f *fileDB) Read(filename string) (io.Reader, error) {
file := f.generateFilePath(filename)
fd, err := os.OpenFile(file, os.O_RDONLY, 0644)
if err != nil {
log.Println("Cannot open file ", file)
return nil, errors.New("No data available at " + file)
}
data, err := ioutil.ReadAll(fd)
if err != nil {
log.Println("Error reading file ", file)
return nil, errors.New("Error reading file " + file)
}
reader := bytes.NewReader(data)
fd.Close()
return reader, nil
}
func (f *fileDB) Write(ticker string, data []byte) error {
if _, ok := f.writer[ticker]; !ok {
file := f.generateFilePath(ticker)
fd, err := os.OpenFile(file, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err != nil {
log.Println("Cannot open file ", file)
return errors.New("Cannot open file for write " + file)
}
f.writer[ticker] = fd
}
f.writer[ticker].Write(data)
return nil
}