-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconfig.go
71 lines (60 loc) · 1.32 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
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"os"
"os/user"
)
// Config has api access token.
type Config struct {
AccessToken string
AccessTokenSecret string
ScreenName string
}
// LoadConfig load json from local.
func LoadConfig() *Config {
config := &Config{}
path := configFilePath()
if fileExists(path) {
data, err := ioutil.ReadFile(path)
if err == nil {
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.Decode(config)
}
}
return config
}
// Save config to local
func (config *Config) Save() bool {
json, err := json.Marshal(config)
if err != nil {
return false
}
ioutil.WriteFile(configFilePath(), json, 0644)
return true
}
// IsAuthenticated return whether you authenticated?
func (config *Config) IsAuthenticated() bool {
return config.AccessToken != "" && config.AccessTokenSecret != ""
}
// SetAccessToken set token to config.
func (config *Config) Set(token string, secret string, screenName string) {
config.AccessToken = token
config.AccessTokenSecret = secret
config.ScreenName = screenName
}
func fileExists(path string) bool {
if path == "" {
return false
}
_, err := os.Stat(path)
return os.IsNotExist(err) == false
}
func configFilePath() string {
target, err := user.Current()
if err != nil {
return ""
}
return target.HomeDir + "/.twg"
}