-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
68 lines (59 loc) · 1.27 KB
/
config.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
package grpctl
import (
"encoding/base64"
"os"
"time"
"gopkg.in/yaml.v3"
)
type config struct {
Entries map[string]entry
}
type entry struct {
Descriptor string
Expiry time.Time
}
func (e entry) decodeDescriptor() ([]byte, error) {
return base64.StdEncoding.DecodeString(e.Descriptor)
}
func loadConfig(filename string) (config, error) {
f, err := os.ReadFile(filename)
if err != nil {
a := config{}.save(filename)
return config{}, a
}
var c config
err = yaml.Unmarshal(f, &c)
if err != nil {
return config{}, err
}
c = c.prune()
if err = c.save(filename); err != nil {
return config{}, err
}
return c, nil
}
func (c config) add(filename string, target string, descriptor []byte, dur time.Duration) error {
c.Entries[target] = entry{
Descriptor: base64.StdEncoding.EncodeToString(descriptor),
Expiry: time.Now().Add(dur),
}
return c.save(filename)
}
func (c config) save(filename string) error {
b, err := yaml.Marshal(c)
if err != nil {
return err
}
return os.WriteFile(filename, b, os.ModePerm)
}
func (c config) prune() config {
newEntries := make(map[string]entry, len(c.Entries))
for target, val := range c.Entries {
if val.Expiry.Before(time.Now()) {
continue
}
newEntries[target] = val
}
c.Entries = newEntries
return c
}