forked from ooni/probe-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkvstore.go
44 lines (36 loc) · 1.17 KB
/
kvstore.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
package engine
import (
"bytes"
"os"
"path/filepath"
"github.com/rogpeppe/go-internal/lockedfile"
)
// KVStore is a simple, atomic key-value store. The user of
// probe-engine should supply an implementation of this interface,
// which will be used by probe-engine to store specific data.
type KVStore interface {
Get(key string) (value []byte, err error)
Set(key string, value []byte) (err error)
}
// FileSystemKVStore is a directory based KVStore
type FileSystemKVStore struct {
basedir string
}
// NewFileSystemKVStore creates a new FileSystemKVStore.
func NewFileSystemKVStore(basedir string) (kvs *FileSystemKVStore, err error) {
if err = os.MkdirAll(basedir, 0700); err == nil {
kvs = &FileSystemKVStore{basedir: basedir}
}
return
}
func (kvs *FileSystemKVStore) filename(key string) string {
return filepath.Join(kvs.basedir, key)
}
// Get returns the specified key's value
func (kvs *FileSystemKVStore) Get(key string) ([]byte, error) {
return lockedfile.Read(kvs.filename(key))
}
// Set sets the value of a specific key
func (kvs *FileSystemKVStore) Set(key string, value []byte) error {
return lockedfile.Write(kvs.filename(key), bytes.NewReader(value), 0600)
}