/
test_config.go
119 lines (98 loc) · 2.44 KB
/
test_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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package test
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"reflect"
"strings"
"unicode"
api "github.com/aspose-barcode-cloud/aspose-barcode-cloud-go/barcode"
"github.com/aspose-barcode-cloud/aspose-barcode-cloud-go/barcode/jwt"
)
func camelToUpperSnake(str string) string {
var builder strings.Builder
prevCharWasLower := false
for _, rn := range str {
if unicode.IsUpper(rn) {
if prevCharWasLower {
builder.WriteRune('_')
}
builder.WriteRune(rn)
} else {
builder.WriteRune(unicode.ToUpper(rn))
}
prevCharWasLower = unicode.IsLower(rn)
}
return builder.String()
}
// Config is Configuration
type Config struct {
JwtConfig jwt.Config `json:"jwt"`
APIConfig api.Configuration `json:"api"`
}
// NewTestConfig creates new Config from JSON-file if exists or from ENV
func NewTestConfig(fileName string, envPrefix string) (*Config, error) {
var config *Config
if f, err := os.Open(fileName); os.IsNotExist(err) {
config, err = newConfigFromEnv(envPrefix)
if err != nil {
return nil, err
}
} else {
if err != nil {
return nil, err
}
defer f.Close()
bytes, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
config, err = newConfigFromJSON(bytes)
if err != nil {
return nil, err
}
}
if err := config.JwtConfig.Validate(); err != nil {
return nil, err
}
return config, nil
}
func newConfigFromJSON(bytes []byte) (*Config, error) {
config := Config{
JwtConfig: *jwt.NewConfig("", ""),
APIConfig: *api.NewConfiguration(),
}
err := json.Unmarshal(bytes, &config)
if err != nil {
return nil, err
}
return &config, nil
}
func newConfigFromEnv(prefix string) (*Config, error) {
pConfig := &Config{
JwtConfig: *jwt.NewConfig("", ""),
APIConfig: *api.NewConfiguration(),
}
pRoot := reflect.ValueOf(pConfig)
root := pRoot.Elem()
typeOfRoot := root.Type()
for i := 0; i < typeOfRoot.NumField(); i++ {
outer := root.Field(i)
outerType := outer.Type()
for j := 0; j < outerType.NumField(); j++ {
inner := outer.Field(j)
if inner.Kind() != reflect.String || !inner.CanSet() {
continue
}
envName := fmt.Sprintf("%s_%s_%s", prefix,
camelToUpperSnake(strings.Split(typeOfRoot.Field(i).Tag.Get("json"), ",")[0]),
camelToUpperSnake(strings.Split(outerType.Field(j).Tag.Get("json"), ",")[0]))
if newVal, exists := os.LookupEnv(envName); exists {
fmt.Printf("Set '%s'\n", envName)
inner.SetString(newVal)
}
}
}
return pConfig, nil
}