file.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. var statsREPORT string
  40. statsREPORT = "\n"
  41. Classifier.STATS.Range(func(key interface{}, value interface{}) bool {
  42. statsREPORT += fmt.Sprintf("{\"%s\" : \"%d\"}\n", key.(string), value.(int64))
  43. return true
  44. })
  45. dumpfile := os.Getenv("DUMPFILE")
  46. if dumpfile == "" {
  47. dumpfile = "bayes.json"
  48. }
  49. if DebugLog {
  50. log.Println("DUMP: ", string(tmpJSON)+statsREPORT)
  51. } else {
  52. writeToFile(dumpfile, string(tmpJSON)+statsREPORT)
  53. log.Println("File saved: ", dumpfile)
  54. }
  55. }
  56. func jsonEngine() {
  57. for {
  58. log.Println("Zardoz Seniority: ", ProxyFlow.seniority)
  59. saveBayesToFile()
  60. time.Sleep(1 * time.Minute)
  61. }
  62. }
  63. func init() {
  64. log.Printf("File Engine Starting")
  65. go jsonEngine()
  66. log.Printf("FIle Engine Started")
  67. }