| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"log" |
| 6 |
"os" |
| 7 |
|
| 8 |
"github.com/knadh/koanf/parsers/toml" |
| 9 |
"github.com/knadh/koanf/providers/file" |
| 10 |
"github.com/knadh/koanf/providers/posflag" |
| 11 |
"github.com/knadh/koanf/v2" |
| 12 |
flag "github.com/spf13/pflag" |
| 13 |
) |
| 14 |
|
| 15 |
// Global koanf instance. Use "." as the key path delimiter. This can be "/" or any character. |
| 16 |
var k = koanf.New(".") |
| 17 |
|
| 18 |
func main() { |
| 19 |
// Use the POSIX compliant pflag lib instead of Go's flag lib. |
| 20 |
f := flag.NewFlagSet("config", flag.ContinueOnError) |
| 21 |
f.Usage = func() { |
| 22 |
fmt.Println(f.FlagUsages()) |
| 23 |
os.Exit(0) |
| 24 |
} |
| 25 |
// Path to one or more config files to load into koanf along with some config params. |
| 26 |
f.StringSlice("conf", []string{"mock/mock.toml"}, "path to one or more .toml config files") |
| 27 |
f.String("time", "2020-01-01", "a time string") |
| 28 |
f.String("type", "xxx", "type of the app") |
| 29 |
f.Parse(os.Args[1:]) |
| 30 |
|
| 31 |
// Load the config files provided in the commandline. |
| 32 |
cFiles, _ := f.GetStringSlice("conf") |
| 33 |
for _, c := range cFiles { |
| 34 |
if err := k.Load(file.Provider(c), toml.Parser()); err != nil { |
| 35 |
log.Fatalf("error loading file: %v", err) |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
// "time" and "type" may have been loaded from the config file, but |
| 40 |
// they can still be overridden with the values from the command line. |
| 41 |
// The bundled posflag.Provider takes a flagset from the spf13/pflag lib. |
| 42 |
// Passing the Koanf instance to posflag helps it deal with default command |
| 43 |
// line flag values that are not present in conf maps from previously loaded |
| 44 |
// providers. |
| 45 |
if err := k.Load(posflag.Provider(f, ".", k), nil); err != nil { |
| 46 |
log.Fatalf("error loading config: %v", err) |
| 47 |
} |
| 48 |
|
| 49 |
fmt.Println("time is = ", k.String("time")) |
| 50 |
} |