forked from adrianduke/configr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.go
90 lines (77 loc) · 2 KB
/
example.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"fmt"
"net/mail"
"os"
"path/filepath"
"github.com/adrianduke/configr"
)
const (
EmailFromAddressKey = "email.fromAddress"
EmailSubjectKey = "email.subject"
EmailRetryOnFailKey = "email.retryOnFail"
EmailMaxRetriesKey = "email.maxRetries"
)
type Email struct {
FromAddress string
Subject string
MaxRetries int // Note config.json contains string
RetryOnFail bool // Note config.json contains string
}
func init() {
configr.RequireKey(EmailFromAddressKey, "Email from address", func(v interface{}) error {
_, err := mail.ParseAddress(v.(string))
return err
})
configr.RequireKey(EmailSubjectKey, "Email subject")
configr.RegisterKey(EmailRetryOnFailKey, "Retry sending email if it fails", false)
configr.RegisterKey(EmailMaxRetriesKey, "How many times to retry email resending", 3)
}
func main() {
// Wont work if GOPATH contains multiple DIRs
path := filepath.Join(os.Getenv("GOPATH"), "src/github.com/adrianduke/configr/examples/simple-json/config.json")
configr.AddSource(configr.NewFileSource(path))
if err := configr.Parse(); err != nil {
fmt.Println(err)
os.Exit(1)
}
fromAddress, err := configr.String(EmailFromAddressKey)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
emailSubject, err := configr.String(EmailSubjectKey)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
retryOnFail, err := configr.Bool(EmailRetryOnFailKey)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
maxRetries, err := configr.Int(EmailMaxRetriesKey)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
email := Email{
FromAddress: fromAddress,
Subject: emailSubject,
MaxRetries: maxRetries,
RetryOnFail: retryOnFail,
}
fmt.Printf("Gotten values:\n\t%#v\n\n", email)
//
// Generate blank config
//
f := configr.NewFileSource("")
f.SetEncoding(configr.JSON)
// f implements the encoder interface
configBytes, err := configr.GenerateBlank(f)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("Blank config:\n%s", string(configBytes))
}