-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsonfile.go
55 lines (50 loc) · 1.2 KB
/
jsonfile.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
package pvc
import (
"encoding/json"
"fmt"
"os"
)
// Default mapping for this backend
const (
DefaultJSONFileMapping = "{{ .ID }}"
)
type jsonFileBackendGetter struct {
mapper SecretMapper
config *jsonFileBackend
contents map[string]string
}
func newjsonFileBackendGetter(jb *jsonFileBackend) (*jsonFileBackendGetter, error) {
f, err := os.Open(jb.fileLocation)
if err != nil {
return nil, fmt.Errorf("error opening file: %v", err)
}
defer f.Close()
c := map[string]string{}
d := json.NewDecoder(f)
err = d.Decode(&c)
if err != nil {
return nil, fmt.Errorf("error decoding file (must be a JSON object): %v", err)
}
if jb.mapping == "" {
jb.mapping = DefaultJSONFileMapping
}
sm, err := newSecretMapper(jb.mapping)
if err != nil {
return nil, fmt.Errorf("error with mapping: %v", err)
}
return &jsonFileBackendGetter{
mapper: sm,
config: jb,
contents: c,
}, nil
}
func (jbg *jsonFileBackendGetter) Get(id string) ([]byte, error) {
key, err := jbg.mapper.MapSecret(id)
if err != nil {
return nil, fmt.Errorf("error mapping id to object key: %v", err)
}
if val, ok := jbg.contents[key]; ok {
return []byte(val), nil
}
return nil, fmt.Errorf("secret not found: %v", key)
}