-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
74 lines (58 loc) · 1.53 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
package timestream
import (
"encoding/json"
"fmt"
"github.com/mstoykov/envconfig"
)
type Config struct {
Region string `envconfig:"K6_TIMESTREAM_REGION" json:"region"`
DatabaseName string `envconfig:"K6_TIMESTREAM_DATABASE_NAME" json:"databaseName"`
TableName string `envconfig:"K6_TIMESTREAM_TABLE_NAME" json:"tableName"`
}
func NewConfig() Config {
c := Config{}
return c
}
func (c Config) apply(cfg Config) Config {
if len(cfg.Region) > 0 {
c.Region = cfg.Region
}
if len(cfg.DatabaseName) > 0 {
c.DatabaseName = cfg.DatabaseName
}
if len(cfg.TableName) > 0 {
c.TableName = cfg.TableName
}
return c
}
func parseJSON(data json.RawMessage) (Config, error) {
conf := Config{}
if err := json.Unmarshal(data, &conf); err != nil {
return conf, fmt.Errorf("unable to parse json: %w", err)
}
return conf, nil
}
// GetConsolidatedConfig combines {default config values + JSON config +
// environment vars config values}, and returns the final result.
func GetConsolidatedConfig(
jsonRawConf json.RawMessage,
env map[string]string,
) (Config, error) {
result := NewConfig()
if jsonRawConf != nil {
jsonConf, err := parseJSON(jsonRawConf)
if err != nil {
return result, fmt.Errorf("unable to parse json config: %w", err)
}
result = result.apply(jsonConf)
}
envConfig := Config{}
if err := envconfig.Process("", &envConfig, func(key string) (string, bool) {
v, ok := env[key]
return v, ok
}); err != nil {
return result, err
}
result = result.apply(envConfig)
return result, nil
}