-
Notifications
You must be signed in to change notification settings - Fork 0
/
structconf.go
67 lines (53 loc) · 1.49 KB
/
structconf.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 structconf
import (
"context"
"flag"
"github.com/kevinfalting/structconf/confhandler"
"github.com/kevinfalting/structconf/stronf"
)
// Parse will set any settable fields in the provided struct based on the
// results of the default handlers. By default, it checks for environment
// variables, default, and required tags. Flags are optionally enabled.
func Parse(ctx context.Context, cfg any, optionFuncs ...optionFunc) error {
fields, err := stronf.SettableFields(cfg)
if err != nil {
return err
}
var opt option
for _, optionFunc := range optionFuncs {
optionFunc(&opt)
}
handlers := []stronf.HandleFunc{
confhandler.EnvironmentVariable{}.Handle,
}
if opt.flagSet != nil {
flagHandler := confhandler.NewFlag(opt.flagSet)
if err := flagHandler.DefineFlags(fields); err != nil {
return err
}
handlers = append(handlers, flagHandler.Handle)
}
handlers = append(handlers,
confhandler.Default{}.Handle,
confhandler.Required{}.Handle,
)
handler := stronf.CombineHandlers(handlers...)
for _, field := range fields {
if err := field.Parse(ctx, handler); err != nil {
return err
}
}
return nil
}
type option struct {
flagSet *flag.FlagSet
}
type optionFunc func(opt *option)
// WithFlagSet will signal to use the [confhandler.Flag] and optionally pass it
// a [flag.FlagSet]. Passing a nil flagset will create and use one similar to
// the stdlib flagset.
func WithFlagSet(fset *flag.FlagSet) optionFunc {
return func(opt *option) {
opt.flagSet = fset
}
}