-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfiles.go
79 lines (69 loc) · 1.65 KB
/
files.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
package main
import (
"encoding/json"
"github.com/spf13/afero"
)
const (
defaultAddress = ":8080"
defaultHTTPMethod = "GET"
defaultLatency = "0ms"
defaultHTTPStatusCode = 200
)
type ConfigFile struct {
Addr string `json:"address"`
Responses []Response `json:"responses"`
}
type Response struct {
Status int `json:"status"`
Method string `json:"method"`
Path string `json:"path"`
Latency string `json:"latency"`
JsonBody string `json:"json_body"`
}
func (c *ConfigFile) enforceDefaults() {
if c.Addr == "" {
c.Addr = defaultAddress
}
for i := range c.Responses {
if c.Responses[i].Method == "" {
c.Responses[i].Method = defaultHTTPMethod
}
if c.Responses[i].Latency == "" {
c.Responses[i].Latency = defaultLatency
}
if c.Responses[i].Status == 0 {
c.Responses[i].Status = defaultHTTPStatusCode
}
}
}
func loadConfig(fs afero.Fs, path string) (ConfigFile, error) {
file, err := afero.ReadFile(fs, path)
if err != nil {
return ConfigFile{}, err
}
configFile := ConfigFile{}
err = json.Unmarshal(file, &configFile)
if err != nil {
return ConfigFile{}, err
}
configFile.enforceDefaults()
return configFile, nil
}
func isFirstRun(fs afero.Fs, path string) (bool, error) {
exists, err := afero.Exists(fs, path)
if err != nil {
return false, err
}
return !exists, nil
}
func configureFirstRun(fs afero.Fs, path string) error {
err := afero.WriteFile(fs, path, []byte(DefaultConfigurationFileContent), 0644)
if err != nil {
return err
}
err = afero.WriteFile(fs, CustomBodyExampleFileName, []byte(CustomBodyExampleFileContent), 0644)
if err != nil {
return err
}
return nil
}