zardoz/file.go
2019-12-09 16:33:58 +01:00

97 行
1.6 KiB
Go

package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"os"
"time"
)
// WriteToFile will print any string of text to a file safely by
// checking for errors and syncing at the end.
func writeToFile(filename string, data string) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
_, err = io.WriteString(file, data)
if err != nil {
return err
}
return file.Sync()
}
func handlepanic() {
if a := recover(); a != nil {
fmt.Println("OPS!: Recovering from:", a)
}
}
func saveBayesToFile() {
log.Println("Trying to write json file")
var jsnBuf = new(bytes.Buffer)
var tmpJSON string
Classifier.busy.Lock()
DumpJSON, err := Classifier.bayez.MarshalJSON()
if err != nil {
DumpJSON = []byte(err.Error())
}
Classifier.busy.Unlock()
log.Println("Raw dump of Classifier: ", string(DumpJSON))
jerr := json.Indent(jsnBuf, DumpJSON, "", " ")
if jerr == nil {
tmpJSON = jsnBuf.String()
} else {
tmpJSON = jerr.Error()
}
fmt.Println(time.Now().String())
Classifier.STATS.Range(func(key interface{}, value interface{}) bool {
fmt.Printf("%s : %d\n", key.(string), value.(int64))
return true
})
dumpfile := os.Getenv("DUMPFILE")
if dumpfile == "" {
dumpfile = "bayes.json"
}
if DebugLog {
log.Println(tmpJSON)
} else {
writeToFile(dumpfile, tmpJSON)
log.Println("File saved: ", dumpfile)
}
}
func jsonEngine() {
for {
log.Println("Zardoz Seniority: ", ProxyFlow.seniority)
saveBayesToFile()
time.Sleep(1 * time.Minute)
}
}
func init() {
log.Printf("File Engine Starting")
go jsonEngine()
log.Printf("FIle Engine Started")
}