-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
67 lines (54 loc) · 1.71 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
package config
import (
"fmt"
"os"
"github.com/alecthomas/kong"
"github.com/go-playground/validator/v10"
server "github.com/michaljurecko/ch-demo/internal/pkg/app/demo/server/config"
"github.com/michaljurecko/ch-demo/internal/pkg/common/dataverse/webapi"
logger "github.com/michaljurecko/ch-demo/internal/pkg/common/log/config"
redis "github.com/michaljurecko/ch-demo/internal/pkg/common/redis/config"
telemetry "github.com/michaljurecko/ch-demo/internal/pkg/common/telemetry/config"
)
type Config struct {
Logger logger.Config `embed:"" prefix:"logger-"`
Telemetry telemetry.Config `embed:"" prefix:"telemetry-"`
Server server.Config `embed:"" prefix:"server-"`
Model webapi.Config `embed:"" prefix:"model-"`
Redis redis.Config `embed:"" prefix:"redis-"`
}
type Decorator func(Config) (Config, error)
func Load(validator *validator.Validate) (Config, error) {
return doLoad(validator, os.Args[1:], nil)
}
func ForTest(validator *validator.Validate, fn Decorator) (Config, error) {
return doLoad(validator, nil, fn)
}
func doLoad(validator *validator.Validate, args []string, decorator Decorator, options ...kong.Option) (Config, error) {
cfg := Config{}
options = append(
options,
kong.Description("Note: Each flag can be set as an ENV."),
kong.DefaultEnvars("DEMO"),
)
parser, err := kong.New(&cfg, options...)
if err != nil {
return Config{}, err
}
_, err = parser.Parse(args)
if err != nil {
return Config{}, err
}
// Decorate
if decorator != nil {
cfg, err = decorator(cfg)
if err != nil {
return Config{}, err
}
}
// Validate
if err := validator.Struct(cfg); err != nil {
return Config{}, fmt.Errorf("config is invalid: %w", err)
}
return cfg, nil
}