forked from agtorre/go-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
66 lines (53 loc) · 1.34 KB
/
main.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"github.com/agtorre/go-cookbook/chapter2/envvar"
)
// Config will hold the config we
// capture from a json file and env vars
type Config struct {
Version string `json:"version" required:"true"`
IsSafe bool `json:"is_safe" default:"true"`
Secret string `json:"secret"`
}
func main() {
var err error
// create a temporary file to hold
// an example json file
tf, err := ioutil.TempFile("", "tmp")
if err != nil {
panic(err)
}
defer tf.Close()
defer os.Remove(tf.Name())
// create a json file to hold
// our secrets
secrets := `{
"secret": "so so secret"
}`
if _, err = tf.Write(bytes.NewBufferString(secrets).Bytes()); err != nil {
panic(err)
}
// We can easily set environment variables
// as needed
if err = os.Setenv("EXAMPLE_VERSION", "1.0.0"); err != nil {
panic(err)
}
if err = os.Setenv("EXAMPLE_ISSAFE", "false"); err != nil {
panic(err)
}
c := Config{}
if err = envvar.LoadConfig(tf.Name(), "EXAMPLE", &c); err != nil {
panic(err)
}
fmt.Println("secrets file contains =", secrets)
// We can also read them
fmt.Println("EXAMPLE_VERSION =", os.Getenv("EXAMPLE_VERSION"))
fmt.Println("EXAMPLE_ISSAFE =", os.Getenv("EXAMPLE_ISSAFE"))
// The final config is a mix of json and environment
// variables
fmt.Printf("Final Config: %#v\n", c)
}