forked from observIQ/stanza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
90 lines (72 loc) · 2.12 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//go:generate mockery --name=Builder --output=../testutil --outpkg=testutil --filename=operator_builder.go --structname=OperatorBuilder
package operator
import (
"encoding/json"
"fmt"
)
// Config is the configuration of an operator
type Config struct {
Builder
}
// Builder is an entity that can build a single operator
type Builder interface {
ID() string
Type() string
Build(BuildContext) ([]Operator, error)
}
// UnmarshalJSON will unmarshal a config from JSON.
func (c *Config) UnmarshalJSON(bytes []byte) error {
var typeUnmarshaller struct {
Type string
}
if err := json.Unmarshal(bytes, &typeUnmarshaller); err != nil {
return err
}
if typeUnmarshaller.Type == "" {
return fmt.Errorf("missing required field 'type'")
}
builderFunc, ok := DefaultRegistry.Lookup(typeUnmarshaller.Type)
if !ok {
return fmt.Errorf("unsupported type '%s'", typeUnmarshaller.Type)
}
builder := builderFunc()
if err := json.Unmarshal(bytes, builder); err != nil {
return fmt.Errorf("unmarshal to %s: %s", typeUnmarshaller.Type, err)
}
c.Builder = builder
return nil
}
// MarshalJSON will marshal a config to JSON.
func (c Config) MarshalJSON() ([]byte, error) {
return json.Marshal(c.Builder)
}
// UnmarshalYAML will unmarshal a config from YAML.
func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
rawConfig := map[string]interface{}{}
err := unmarshal(&rawConfig)
if err != nil {
return fmt.Errorf("failed to unmarshal yaml to base config: %s", err)
}
typeInterface, ok := rawConfig["type"]
if !ok {
return fmt.Errorf("missing required field 'type'")
}
typeString, ok := typeInterface.(string)
if !ok {
return fmt.Errorf("non-string type %T for field 'type'", typeInterface)
}
builderFunc, ok := DefaultRegistry.Lookup(typeString)
if !ok {
return fmt.Errorf("unsupported type '%s'", typeString)
}
builder := builderFunc()
if err = unmarshal(builder); err != nil {
return fmt.Errorf("unmarshal to %s: %s", typeString, err)
}
c.Builder = builder
return nil
}
// MarshalYAML will marshal a config to YAML.
func (c Config) MarshalYAML() (interface{}, error) {
return c.Builder, nil
}