forked from YanxinTang/clipboard-online
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
75 lines (65 loc) · 1.78 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
package main
import (
"encoding/json"
"io/ioutil"
"github.com/YanxinTang/clipboard-online/utils"
"github.com/sirupsen/logrus"
)
const ConfigFile = "config.json"
const LogFile = "log.txt"
// Config represents configuration for applicaton
type Config struct {
Port string `json:"port"`
Authkey string `json:"authkey"`
AuthkeyExpiredTimeout int64 `json:"authkeyExpiredTimeout"`
LogLevel logrus.Level `json:"logLevel"`
TempDir string `json:"tempDir"`
ReserveHistory bool `json:"reserveHistory"`
Notify ConfigNotify `json:"notify"`
}
type ConfigNotify struct {
Copy bool `json:"copy"`
Paste bool `json:"paste"`
}
// DefaultConfig is a default configuration for application
var DefaultConfig = Config{
Port: "8086",
Authkey: "",
AuthkeyExpiredTimeout: 30,
LogLevel: logrus.WarnLevel,
TempDir: "./temp",
ReserveHistory: false,
Notify: ConfigNotify{
Copy: false,
Paste: false,
},
}
func loadConfig(path string) (*Config, error) {
if utils.IsExistFile(path) {
return loadConfigFromFile(path)
}
if err := createConfigFile(path); err != nil {
return nil, err
}
return &DefaultConfig, nil
}
func loadConfigFromFile(path string) (*Config, error) {
configBytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
if err := json.Unmarshal(configBytes, &DefaultConfig); err != nil {
return nil, err
}
return &DefaultConfig, nil
}
func createConfigFile(path string) error {
defaultConfigJSON, err := json.MarshalIndent(DefaultConfig, "", " ")
if err != nil {
return err
}
if err := ioutil.WriteFile(path, []byte(defaultConfigJSON), 0744); err != nil {
return err
}
return nil
}