forked from st3v/go-plugins
/
runtimevar.go
64 lines (51 loc) · 1.18 KB
/
runtimevar.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
// package runtimevar is the source for gocloud.dev/runtimevar
package runtimevar
import (
"context"
"fmt"
"sync"
"github.com/micro/go-micro/config/source"
"gocloud.dev/runtimevar"
)
type rvSource struct {
opts source.Options
sync.Mutex
v *runtimevar.Variable
}
func (rv *rvSource) Read() (*source.ChangeSet, error) {
s, err := rv.v.Latest(context.Background())
if err != nil {
return nil, err
}
// assuming value is bytes
b, err := rv.opts.Encoder.Encode(s.Value.([]byte))
if err != nil {
return nil, fmt.Errorf("error reading source: %v", err)
}
cs := &source.ChangeSet{
Timestamp: s.UpdateTime,
Format: rv.opts.Encoder.String(),
Source: rv.String(),
Data: b,
}
cs.Checksum = cs.Sum()
return cs, nil
}
func (rv *rvSource) Watch() (source.Watcher, error) {
return newWatcher(rv.String(), rv.v, rv.opts)
}
func (rv *rvSource) String() string {
return "runtimevar"
}
func NewSource(opts ...source.Option) source.Source {
options := source.NewOptions(opts...)
v, ok := options.Context.Value(variableKey{}).(*runtimevar.Variable)
if !ok {
// nooooooo
panic("runtimevar.Variable required")
}
return &rvSource{
opts: options,
v: v,
}
}