forked from gliderlabs/logspout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
persist.go
78 lines (69 loc) · 1.76 KB
/
persist.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
package router
import (
"encoding/json"
"io"
"io/ioutil"
"log"
"os"
"strings"
)
// RouteFileStore represents a directory for storing routes
type RouteFileStore string
// Filename returns the filename in a RouteFileStore for a given id
func (fs RouteFileStore) Filename(id string) string {
return string(fs) + "/" + id + ".json"
}
// Get returns *Route based on an id
func (fs RouteFileStore) Get(id string) (*Route, error) {
file, err := os.Open(fs.Filename(id))
if err != nil {
return nil, err
}
route := new(Route)
if err = unmarshal(file, route); err != nil {
return nil, err
}
return route, nil
}
// GetAll returns a slice of *Route for the entire RouteFileStore
func (fs RouteFileStore) GetAll() ([]*Route, error) {
files, err := ioutil.ReadDir(string(fs))
if err != nil {
return nil, err
}
var routes []*Route
for _, file := range files {
fileparts := strings.Split(file.Name(), ".")
if len(fileparts) > 1 && fileparts[1] == "json" {
route, err := fs.Get(fileparts[0])
if err == nil {
routes = append(routes, route)
}
}
}
return routes, nil
}
// Add writes a marshalled *Route to the RouteFileStore
func (fs RouteFileStore) Add(route *Route) error {
return ioutil.WriteFile(fs.Filename(route.ID), marshal(route), 0644)
}
// Remove removes route from the RouteFileStore based on id
func (fs RouteFileStore) Remove(id string) bool {
if _, err := os.Stat(fs.Filename(id)); err == nil {
if err := os.Remove(fs.Filename(id)); err != nil {
return true
}
}
return false
}
func marshal(obj interface{}) []byte {
bytes, err := json.MarshalIndent(obj, "", " ")
if err != nil {
log.Println("marshal:", err)
}
return bytes
}
func unmarshal(input io.Reader, obj interface{}) error {
dec := json.NewDecoder(input)
return dec.Decode(obj)
}