-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
80 lines (68 loc) · 2.15 KB
/
json.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
package oconfig
import (
"encoding/json"
"fmt"
"os"
)
// ParseJSON parses a JSON file and returns a Config struct.
func ParseJSON(file string) (Config, error) {
var cfg Config
data, err := os.ReadFile(file)
if err != nil {
if err = CreateJSON(file); err != nil {
return cfg, err
}
return DefaultConfig, fmt.Errorf("config file created - please fill in required fields")
}
// Decode the JSON file into a Config struct.
if err := json.Unmarshal(data, &cfg); err != nil {
return cfg, fmt.Errorf("unable to parse config file: %v", err)
}
// We re-write the config file to ensure all fields are present.
if updated, err := WriteJSON(file, cfg); err != nil {
return cfg, fmt.Errorf("unable to re-write config file: %v", err)
} else if updated {
// If the config file was updated, we need to re-parse it to ensure the Config struct is up-to-date.
return ParseJSON(file)
}
return cfg, nil
}
// CreateJSON creates a new JSON file with default config.
func CreateJSON(file string) error {
// Create a new config file
_, err := os.Create(file)
if err != nil {
return fmt.Errorf("unable to create config file: %v", err)
}
// Write default config to file.
dat, err := json.MarshalIndent(DefaultConfig, "", " ")
if err != nil {
return fmt.Errorf("unable to write default config to file: %v", err)
}
if err := os.WriteFile(file, dat, 0644); err != nil {
return fmt.Errorf("unable to write default config to file: %v", err)
}
return nil
}
// WriteJSON writes a Config struct to a JSON file.
func WriteJSON(file string, cfg Config) (bool, error) {
var updated bool
switch cfg.Version {
case "": // The first version of the config did not have the version field.
newCfg := DefaultConfig
newCfg.AuthKey = cfg.AuthKey
newCfg.Branch = cfg.Branch
newCfg.LocalAddress = cfg.LocalAddress
newCfg.RemoteAddress = cfg.RemoteAddress
cfg = newCfg
updated = true
}
dat, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return updated, fmt.Errorf("unable to write config to file: %v", err)
}
if err := os.WriteFile(file, dat, 0644); err != nil {
return updated, fmt.Errorf("unable to write config to file: %v", err)
}
return updated, nil
}