-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
85 lines (67 loc) · 1.43 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
package main
import (
"encoding/json"
"os"
"sync"
)
// GithubConfig struct represents configuration for GithubRespecter
type GithubConfig struct {
Username string `json:"username"`
Token string `json:"token"`
}
// Config struct for working with configuration
type Config struct {
Github GithubConfig `json:"github"`
}
// ConfigStorage struct saves and loads config
type ConfigStorage struct {
FilePath string
m *sync.RWMutex
}
// NewConfigStorage func creates new config storage
// If we will not pass file path then we work in-memory
func NewConfigStorage(filePath string) *ConfigStorage {
return &ConfigStorage{
FilePath: filePath,
m: &sync.RWMutex{},
}
}
// Load function creates new config
func (cs *ConfigStorage) Load() *Config {
c := &Config{}
if cs.FilePath == "" {
return c
}
cs.m.RLock()
defer cs.m.RUnlock()
file, err := os.Open(cs.FilePath)
defer file.Close()
if err != nil {
return c
}
decoder := json.NewDecoder(file)
decoder.Decode(&c)
return c
}
// Save func writes config file if we know it's name
func (cs *ConfigStorage) Save(c *Config) error {
if cs.FilePath == "" {
return nil
}
cs.m.Lock()
defer cs.m.Unlock()
file, err := os.Open(cs.FilePath)
defer file.Close()
if os.IsNotExist(err) {
file, err = os.Create(cs.FilePath)
}
if err != nil {
return err
}
encoder := json.NewEncoder(file)
err = encoder.Encode(c)
if err != nil {
return err
}
return nil
}