1
0
Fork 0

Save indented JSON

This commit is contained in:
Gregory Eremin 2015-08-29 19:50:22 +03:00
parent d3d78f06b4
commit 2dc27e62c5
2 changed files with 23 additions and 9 deletions

View File

@ -29,10 +29,8 @@ func writeFile(file string, body []byte) error {
if err = mkdirp(file); err != nil {
return err
}
if fd, err = os.Create(file); err != nil {
return err
}
} else if fd, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, filePerm); err != nil {
}
if fd, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, filePerm); err != nil {
return err
}
defer fd.Close()

View File

@ -1,6 +1,7 @@
package secondly
import (
"bytes"
"encoding/json"
"flag"
"fmt"
@ -122,11 +123,7 @@ func readConfig() {
}
func writeConfig() {
body, err := json.Marshal(config)
if err != nil {
panic(err)
}
if err = writeFile(configFile, body); err != nil {
if err := writeFile(configFile, marshal(config)); err != nil {
panic(err)
}
}
@ -144,6 +141,25 @@ func updateConfig(body []byte) {
config = dupe
}
func marshal(obj interface{}) []byte {
body, err := json.Marshal(config)
if err != nil {
panic(err)
}
out := bytes.NewBuffer([]byte{})
// Indent with empty prefix and four spaces
if err = json.Indent(out, body, "", " "); err != nil {
panic(err)
}
// Adding a trailing newline
// It's good for your carma
out.WriteByte('\n')
return out.Bytes()
}
func triggerCallbacks(oldConf, newConf interface{}) {
// Don't trigger callbacks on fist load
if !initialized {