| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"log" |
| 6 |
"os" |
| 7 |
"slices" |
| 8 |
"strings" |
| 9 |
"time" |
| 10 |
|
| 11 |
"github.com/knadh/koanf/parsers/json" |
| 12 |
"github.com/knadh/koanf/providers/env/v2" |
| 13 |
"github.com/knadh/koanf/providers/file" |
| 14 |
"github.com/knadh/koanf/v2" |
| 15 |
) |
| 16 |
|
| 17 |
var k = koanf.New(".") |
| 18 |
|
| 19 |
// Run this example: |
| 20 |
// |
| 21 |
// go run ./examples/read-environment |
| 22 |
// |
| 23 |
// Try setting environment variables to see what changes (and what doesn't!): |
| 24 |
// |
| 25 |
// MYVAR_PARENT1_CHILD1_NAME=FooBar go run ./examples/read-environment |
| 26 |
// MYVAR_TIME=2020-02-02 go run ./examples/read-environment |
| 27 |
// MYVAR_PARENT1_CHILD1_GRANDCHILD1_IDS="3 2 1" go run ./examples/read-environment |
| 28 |
func main() { |
| 29 |
// Load JSON config. |
| 30 |
if err := k.Load(file.Provider("mock/mock.json"), json.Parser()); err != nil { |
| 31 |
log.Fatalf("error loading config: %v", err) |
| 32 |
} |
| 33 |
|
| 34 |
// Load environment variables and merge into the loaded config. |
| 35 |
// "MYVAR" is the prefix to filter the env vars by. |
| 36 |
// "." is the delimiter used to represent the key hierarchy in env vars. |
| 37 |
// The optional TransformFunc can be used to transform the env var names, |
| 38 |
// for instance, to lowercase them. Values can also be modified into types |
| 39 |
// other than strings, for example, to turn space separated env vars into |
| 40 |
// slices. |
| 41 |
// |
| 42 |
// will be merged into the "type" and the nested "parent1.child1.name" |
| 43 |
// For example, env vars: MYVAR_TYPE and MYVAR_PARENT1_CHILD1_NAME |
| 44 |
// keys in the config file here as we lowercase the key, |
| 45 |
// replace `_` with `.` and strip the MYVAR_ prefix so that |
| 46 |
// only "parent1.child1.name" remains. |
| 47 |
// |
| 48 |
// The optional EnvironFunc can be used to control what environment |
| 49 |
// variables are read by Koanf. In this example, we ensure that the time |
| 50 |
// variable cannot be overridden by env vars. |
| 51 |
k.Load(env.Provider(".", env.Opt{ |
| 52 |
Prefix: "MYVAR_", |
| 53 |
TransformFunc: func(k, v string) (string, any) { |
| 54 |
k = strings.ReplaceAll(strings.ToLower( |
| 55 |
strings.TrimPrefix(k, "MYVAR_")), "_", ".") |
| 56 |
|
| 57 |
// If there is a space in the value, split the value into a slice by the space. |
| 58 |
if strings.Contains(v, " ") { |
| 59 |
return k, strings.Split(v, " ") |
| 60 |
} |
| 61 |
return k, v |
| 62 |
}, |
| 63 |
EnvironFunc: func() []string { |
| 64 |
return slices.DeleteFunc(os.Environ(), func(s string) bool { |
| 65 |
return strings.HasPrefix(s, "MYVAR_TIME") |
| 66 |
}) |
| 67 |
}, |
| 68 |
}), nil) |
| 69 |
|
| 70 |
fmt.Println("name is =", k.String("parent1.child1.name")) |
| 71 |
fmt.Println("time is =", k.Time("time", time.DateOnly)) |
| 72 |
fmt.Println("ids are =", k.Strings("parent1.child1.grandchild1.ids")) |
| 73 |
} |