-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
65 lines (59 loc) · 1.18 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
63
64
65
package main
import (
"encoding/json"
"fmt"
"os"
"path"
)
const (
ConfigPrefsFile = "prefs.json"
)
type ConfigJSON struct {
Email, Token string
}
func CreateConfigDirIfNotExists() error {
_, err := os.Stat(ConfigDir)
if err == nil {
return nil
}
if !os.IsNotExist(err) {
return fmt.Errorf("could not stat config directory, %v", err)
}
return os.MkdirAll(ConfigDir, 0700)
}
func LoadConfig() error {
f, err := os.Open(path.Join(ConfigDir, ConfigPrefsFile))
if err != nil {
if err == os.ErrNotExist {
return nil
}
return fmt.Errorf("could not open prefs file, %v", err)
}
r := json.NewDecoder(f)
conf := ConfigJSON{}
if err := r.Decode(&conf); err != nil {
return fmt.Errorf("could not read prefs file, %v", err)
}
Email = conf.Email
Token = conf.Token
return nil
}
func SaveConfig() error {
conf := ConfigJSON{
Email: Email,
Token: Token,
}
f, err := os.OpenFile(
path.Join(ConfigDir, ConfigPrefsFile),
os.O_CREATE|os.O_WRONLY,
0600,
)
if err != nil {
return fmt.Errorf("could not open prefs file, %v", err)
}
w := json.NewEncoder(f)
if err := w.Encode(conf); err != nil {
return fmt.Errorf("could not write prefs file, %v", err)
}
return nil
}