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,13 +40,22 @@ func bootstrap() {
} }
if fileExist(configFile) { if fileExist(configFile) {
log.Println("Loading config file") log.Println("Loading config file")
readConfig()
} else {
log.Println("Config file not found, saving an empty one")
writeConfig()
}
}
func readConfig() {
body, err := readFile(configFile) body, err := readFile(configFile)
if err != nil { if err != nil {
panic(err) panic(err)
} }
update(body) updateConfig(body)
} else { }
log.Println("Config file not found, saving an empty one")
func writeConfig() {
body, err := json.Marshal(config) body, err := json.Marshal(config)
if err != nil { if err != nil {
panic(err) panic(err)
@ -54,10 +63,9 @@ func bootstrap() {
if err = writeFile(configFile, body); err != nil { if err = writeFile(configFile, body); err != nil {
panic(err) panic(err)
} }
}
} }
func update(body []byte) { 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" {