-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.go
96 lines (76 loc) · 1.77 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
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
91
92
93
94
95
96
package config
import (
"encoding/json"
"os"
"path/filepath"
"time"
"github.com/kirsle/configdir"
)
type AppSettings struct {
AccessToken string
RefreshToken string
Expires time.Time
}
func New() AppSettings {
configPath := configdir.LocalConfig("openbin")
// create the config file if it doesn't exist
if err := configdir.MakePath(configPath); err != nil {
panic(err)
}
configFile := filepath.Join(configPath, "settings.json")
var settings AppSettings
// create the config file if it doesn't exist
if _, err := os.Stat(configFile); os.IsNotExist(err) {
// Create the new config file.
settings = AppSettings{}
fh, err := os.Create(configFile)
if err != nil {
panic(err)
}
defer fh.Close()
encoder := json.NewEncoder(fh)
encoder.Encode(&settings)
} else {
// Load the existing file.
fh, err := os.Open(configFile)
if err != nil {
panic(err)
}
defer fh.Close()
decoder := json.NewDecoder(fh)
decoder.Decode(&settings)
}
return settings
}
func (s *AppSettings) Save() {
configPath := configdir.LocalConfig("openbin")
configFile := filepath.Join(configPath, "settings.json")
fh, err := os.OpenFile(configFile, os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
panic(err)
}
defer fh.Close()
encoder := json.NewEncoder(fh)
encoder.Encode(s)
}
func (s *AppSettings) SetAccessToken(token string) {
s.AccessToken = token
s.Save()
}
func (s *AppSettings) SetRefreshToken(token string) {
s.RefreshToken = token
s.Save()
}
func (s *AppSettings) GetAccessToken() string {
return s.AccessToken
}
func (s *AppSettings) GetRefreshToken() string {
return s.RefreshToken
}
func (s *AppSettings) SetTokenExpiry(expiry time.Time) {
s.Expires = expiry
s.Save()
}
func (s *AppSettings) GetTokenExpiry() time.Time {
return s.Expires
}