file.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. dumpfile := os.Getenv("DUMPFILE")
  40. if dumpfile == "" {
  41. dumpfile = "bayes.json"
  42. }
  43. if DebugLog {
  44. log.Println("DUMP: ", string(tmpJSON))
  45. } else {
  46. writeToFile(dumpfile, string(tmpJSON))
  47. log.Println("File saved: ", dumpfile)
  48. }
  49. }
  50. func jsonEngine() {
  51. for {
  52. log.Println("Zardoz Seniority: ", ProxyFlow.seniority)
  53. saveBayesToFile()
  54. time.Sleep(1 * time.Minute)
  55. }
  56. }
  57. func init() {
  58. log.Printf("File Engine Starting")
  59. go jsonEngine()
  60. log.Printf("FIle Engine Started")
  61. }