-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathconfig_validation.go
51 lines (43 loc) · 1.18 KB
/
config_validation.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
package common
import (
"encoding/json"
jsonschema_generator "github.com/invopop/jsonschema"
jsonschema_validator "github.com/santhosh-tekuri/jsonschema/v5"
"github.com/sirupsen/logrus"
)
var configSchema *jsonschema_validator.Schema
func init() {
defer func() {
if r := recover(); r != nil {
// Config validation is best-effort
logrus.Warningf("Something went wrong creating config schema: %v", r)
}
}()
r := &jsonschema_generator.Reflector{
RequiredFromJSONSchemaTags: true,
}
schema, err := json.Marshal(r.Reflect(&Config{}))
if err != nil {
panic(err)
}
configSchema = jsonschema_validator.MustCompileString("config_schema.json", string(schema))
}
func Validate(config *Config) error {
defer func() {
if r := recover(); r != nil {
// Config validation is best-effort
logrus.Warningf("Something went wrong validating config: %v", r)
}
}()
// Validation must be done on generic types so we re-unmarshal the config into an interface{}
configString, err := json.Marshal(config)
if err != nil {
panic(err)
}
var jsonValue interface{}
err = json.Unmarshal(configString, &jsonValue)
if err != nil {
panic(err)
}
return configSchema.Validate(jsonValue)
}