1
0
Fork 0

Split bootstrap into readConfig and writeConfig functions

This commit is contained in:
Gregory Eremin 2015-08-29 14:00:06 +03:00
parent 16b8a8f4df
commit 605d3e5b50
2 changed files with 27 additions and 16 deletions

View File

@ -40,24 +40,32 @@ func bootstrap() {
} }
if fileExist(configFile) { if fileExist(configFile) {
log.Println("Loading config file") log.Println("Loading config file")
body, err := readFile(configFile) readConfig()
if err != nil {
panic(err)
}
update(body)
} else { } else {
log.Println("Config file not found, saving an empty one") log.Println("Config file not found, saving an empty one")
body, err := json.Marshal(config) writeConfig()
if err != nil {
panic(err)
}
if err = writeFile(configFile, body); err != nil {
panic(err)
}
} }
} }
func update(body []byte) { func readConfig() {
body, err := readFile(configFile)
if err != nil {
panic(err)
}
updateConfig(body)
}
func writeConfig() {
body, err := json.Marshal(config)
if err != nil {
panic(err)
}
if err = writeFile(configFile, body); err != nil {
panic(err)
}
}
func updateConfig(body []byte) {
dupe := duplicate(config) dupe := duplicate(config)
if err := json.Unmarshal(body, dupe); err != nil { if err := json.Unmarshal(body, dupe); err != nil {
log.Println("Failed to update config") log.Println("Failed to update config")

View File

@ -1,6 +1,9 @@
package confection2 package confection2
import "testing" import (
"encoding/json"
"testing"
)
type testConf struct { type testConf struct {
Foo string `json:"foo"` Foo string `json:"foo"`
@ -28,11 +31,11 @@ func TestUnmarshal(t *testing.T) {
conf := testConf{} conf := testConf{}
var i interface{} = &conf var i interface{} = &conf
if err := unmarshal([]byte(badJSON), i); err == nil { if err := json.Unmarshal([]byte(badJSON), i); err == nil {
t.Error("Expected error") t.Error("Expected error")
} }
if err := unmarshal([]byte(goodJSON), i); err != nil { if err := json.Unmarshal([]byte(goodJSON), i); err != nil {
t.Error("Unexpected error") t.Error("Unexpected error")
} }
if conf.Foo != "baz" { if conf.Foo != "baz" {