/
bind_env.go
80 lines (68 loc) · 1.79 KB
/
bind_env.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
package viper
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"strings"
"github.com/spf13/cast"
"github.com/pkg/errors"
"github.com/ory/jsonschema/v3"
"github.com/spf13/viper"
jsonschemax "github.com/mj23978/chat-backend-x/jsonschema"
)
// BindEnvsToSchema uses all keys it can find from ``
func BindEnvsToSchema(schema json.RawMessage) error {
compiler := jsonschema.NewCompiler()
id := fmt.Sprintf("%x.json", sha256.Sum256(schema))
if err := compiler.AddResource(id, bytes.NewReader(schema)); err != nil {
return errors.WithStack(err)
}
compiler.ExtractAnnotations = true
keys, err := jsonschemax.ListPaths(id, compiler)
if err != nil {
return err
}
viper.AutomaticEnv()
viper.SetTypeByDefaultValue(true)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
for _, key := range keys {
if err := viper.BindEnv(key.Name); err != nil {
return errors.WithStack(err)
}
if key.Default != nil {
// key.Default will be of type []interface{} whenever it is an array in the schema
switch key.Type.(type) {
case []string:
def, err := cast.ToStringSliceE(key.Default)
if err != nil {
return errors.WithStack(err)
}
viper.SetDefault(key.Name, def)
case []float64:
switch def := key.Default.(type) {
case []interface{}:
var r []float64
for _, i := range def {
// we first cast to string as json.Number is the type of numbers
s, err := cast.ToStringE(i)
if err != nil {
return errors.WithStack(err)
}
f, err := cast.ToFloat64E(s)
if err != nil {
return errors.WithStack(err)
}
r = append(r, f)
}
viper.SetDefault(key.Name, r)
default:
viper.SetDefault(key.Name, key.Default)
}
default:
viper.SetDefault(key.Name, key.Default)
}
}
}
return nil
}