Use json.Encoder/Decoder directly with file pointer

This commit is contained in:
Julian Kornberger 2016-11-20 18:30:32 +01:00
parent 332e7f5f54
commit 5c2a655b11

View File

@ -2,7 +2,6 @@ package models
import ( import (
"encoding/json" "encoding/json"
"io/ioutil"
"log" "log"
"os" "os"
"sync" "sync"
@ -172,6 +171,20 @@ func (nodes *Nodes) expire() {
} }
} }
func (nodes *Nodes) load() {
path := nodes.config.Nodes.NodesPath
if f, err := os.Open(path); err == nil {
if err := json.NewDecoder(f).Decode(nodes); err == nil {
log.Println("loaded", len(nodes.List), "nodes")
} else {
log.Println("failed to unmarshal nodes:", err)
}
} else {
log.Println("failed to load cached nodes:", err)
}
}
func (nodes *Nodes) save() { func (nodes *Nodes) save() {
// Locking foo // Locking foo
nodes.RLock() nodes.RLock()
@ -216,34 +229,21 @@ func (stats *GlobalStats) Fields() map[string]interface{} {
} }
} }
func (nodes *Nodes) load() { // Marshals the input and writes it into the given file
path := nodes.config.Nodes.NodesPath
log.Println("loading", path)
if filedata, err := ioutil.ReadFile(path); err == nil {
if err = json.Unmarshal(filedata, nodes); err == nil {
log.Println("loaded", len(nodes.List), "nodes")
} else {
log.Println("failed to unmarshal nodes:", err)
}
} else {
log.Println("failed loading cached nodes:", err)
}
}
func save(input interface{}, outputFile string) { func save(input interface{}, outputFile string) {
data, err := json.Marshal(input) tmpFile := outputFile + ".tmp"
f, err := os.OpenFile(tmpFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil { if err != nil {
log.Panic(err) log.Panic(err)
} }
tmpFile := outputFile + ".tmp" err = json.NewEncoder(f).Encode(input)
if err != nil {
if err := ioutil.WriteFile(tmpFile, data, 0644); err != nil {
log.Panic(err) log.Panic(err)
} }
f.Close()
if err := os.Rename(tmpFile, outputFile); err != nil { if err := os.Rename(tmpFile, outputFile); err != nil {
log.Panic(err) log.Panic(err)
} }