file.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log"
  8. "os"
  9. "time"
  10. )
  11. // WriteToFile will print any string of text to a file safely by
  12. // checking for errors and syncing at the end.
  13. func writeToFile(filename string, data string) error {
  14. file, err := os.Create(filename)
  15. if err != nil {
  16. return err
  17. }
  18. defer file.Close()
  19. _, err = io.WriteString(file, data)
  20. if err != nil {
  21. return err
  22. }
  23. return file.Sync()
  24. }
  25. func handlepanic() {
  26. if a := recover(); a != nil {
  27. fmt.Println("OPS!: Recovering from:", a)
  28. }
  29. }
  30. func saveBayesToFile() {
  31. log.Println("Trying to write json file")
  32. var jsnBuf = new(bytes.Buffer)
  33. var tmpJSON string
  34. Classifier.busy.Lock()
  35. DumpJSON, err := Classifier.bayez.MarshalJSON()
  36. if err != nil {
  37. DumpJSON = []byte(err.Error())
  38. }
  39. Classifier.busy.Unlock()
  40. log.Println("Raw dump of Classifier: ", string(DumpJSON))
  41. jerr := json.Indent(jsnBuf, DumpJSON, "", " ")
  42. if jerr == nil {
  43. tmpJSON = jsnBuf.String()
  44. } else {
  45. tmpJSON = jerr.Error()
  46. }
  47. dumpfile := os.Getenv("DUMPFILE")
  48. if dumpfile == "" {
  49. dumpfile = "bayes.json"
  50. }
  51. if DebugLog {
  52. log.Println(tmpJSON)
  53. } else {
  54. writeToFile(dumpfile, tmpJSON)
  55. log.Println("File saved: ", dumpfile)
  56. }
  57. }
  58. func jsonEngine() {
  59. for {
  60. log.Println("Zardoz Seniority: ", ProxyFlow.seniority)
  61. saveBayesToFile()
  62. time.Sleep(1 * time.Minute)
  63. }
  64. }
  65. func init() {
  66. log.Printf("File Engine Starting")
  67. go jsonEngine()
  68. log.Printf("FIle Engine Started")
  69. }