-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetfromenv_example_test.go
More file actions
86 lines (72 loc) · 2.18 KB
/
setfromenv_example_test.go
File metadata and controls
86 lines (72 loc) · 2.18 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2026 Carleton University Library
// All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package setfromenv_test
import (
"flag"
"fmt"
"os"
"testing"
"github.com/cu-library/setfromenv"
)
func TestMain(m *testing.M) {
prefix := "APP_"
envs := []struct {
name string
value string
}{
{"PORT", "9090"},
{"CONFIG_FILE", "my-config.toml"},
}
// Borrowed from the stdlib's cleanup after using testing's t.Setenv().
for _, env := range envs {
key := prefix + env.name
prevValue, ok := os.LookupEnv(key)
err := os.Setenv(key, env.value)
if err != nil {
fmt.Fprintln(os.Stderr, "Could not set environment variable:", err)
os.Exit(1)
}
if ok {
defer os.Setenv(key, prevValue) //nolint:errcheck
} else {
defer os.Unsetenv(key) //nolint:errcheck
}
}
m.Run()
}
func ExampleSetFlagsInFlagSet() {
// We assume the environment variables APP_PORT
// and APP_CONFIG_FILE have been set.
// Normally, we don't need to create a new FlagSet.
// Instead, we use the flag package's CommandLine, which is
// the default set of command-line flags, parsed from os.Args.
fs := flag.NewFlagSet("demo", flag.ContinueOnError)
prefix := "APP"
host := fs.String("host", "localhost", "server host")
port := fs.Int("port", 8080, "server port")
config := fs.String("config-file", "config.toml", "config file")
// Simulate user explicitly setting one flag (port) via parsing args.
_ = fs.Parse([]string{"-port=7777"})
// Set the value of unset flags from the environment.
// Normally, you would use SetFlags(prefix),
// which sets the unset flags from the parsed command line.
// In this example, we need to pass the explicit FlagSet fs.
err := setfromenv.SetFlagsInFlagSet(fs, prefix)
if err != nil {
fmt.Printf("error: %v", err)
return
}
// host should be the default, as it wasn't explicitly set and
// APP_HOST wasn't an environment variable.
fmt.Println(*host)
// port should be the value which was set explicitly.
fmt.Println(*port)
// config should be the value of the environment variable APP_CONFIG_FILE.
fmt.Println(*config)
// Output:
// localhost
// 7777
// my-config.toml
}