file.go 1.4 KB

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