forked from parkr/antispam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
62 lines (49 loc) · 1.44 KB
/
config.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
package main
import (
"encoding/json"
"io"
"log"
"os"
"sort"
"github.com/pkg/errors"
)
type config struct {
Address, Port string `json:",omitempty"`
Username, Password string `json:",omitempty"`
BadEmailDomains, BadEmails []string `json:",omitempty"`
}
func readConfigFile(conf *config, filename string) error {
f, err := os.Open(filename)
if err != nil {
return errors.Wrapf(err, "unable to open file %q", filename)
}
defer f.Close()
if err = json.NewDecoder(f).Decode(conf); err != nil && err != io.EOF {
return errors.Wrapf(err, "unable to read json from %q", filename)
}
sort.Strings(conf.BadEmailDomains)
sort.Strings(conf.BadEmails)
return nil
}
func writeNewFilterFile(filename string, conf *config) {
f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
panic(errors.Wrapf(err, "unable to open file for writing %q", filename))
}
sort.Strings(conf.BadEmailDomains)
sort.Strings(conf.BadEmails)
filterConf := &config{
BadEmailDomains: conf.BadEmailDomains,
BadEmails: conf.BadEmails,
}
encoder := json.NewEncoder(f)
encoder.SetIndent("", " ")
if err = encoder.Encode(filterConf); err != nil {
f.Close()
panic(errors.Wrapf(err, "unable to write json to %q", filename))
}
if err := f.Close(); err != nil {
panic(errors.Wrapf(err, "unable to close file descriptor for %q", filename))
}
log.Printf("Wrote filter config back out to %q", filename)
}