io.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package cedar
  2. import (
  3. "bufio"
  4. "encoding/gob"
  5. "encoding/json"
  6. "io"
  7. "os"
  8. )
  9. // Save saves the cedar to an io.Writer,
  10. // where dataType is either "json" or "gob".
  11. func (da *Cedar) Save(out io.Writer, dataType string) error {
  12. switch dataType {
  13. case "gob", "GOB":
  14. dataEecoder := gob.NewEncoder(out)
  15. return dataEecoder.Encode(da.cedar)
  16. case "json", "JSON":
  17. dataEecoder := json.NewEncoder(out)
  18. return dataEecoder.Encode(da.cedar)
  19. }
  20. return ErrInvalidDataType
  21. }
  22. // SaveToFile saves the cedar to a file,
  23. // where dataType is either "json" or "gob".
  24. func (da *Cedar) SaveToFile(fileName string, dataType string) error {
  25. file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0666)
  26. if err != nil {
  27. return err
  28. }
  29. defer file.Close()
  30. out := bufio.NewWriter(file)
  31. defer out.Flush()
  32. da.Save(out, dataType)
  33. return nil
  34. }
  35. // Load loads the cedar from an io.Writer,
  36. // where dataType is either "json" or "gob".
  37. func (da *Cedar) Load(in io.Reader, dataType string) error {
  38. switch dataType {
  39. case "gob", "GOB":
  40. dataDecoder := gob.NewDecoder(in)
  41. return dataDecoder.Decode(da.cedar)
  42. case "json", "JSON":
  43. dataDecoder := json.NewDecoder(in)
  44. return dataDecoder.Decode(da.cedar)
  45. }
  46. return ErrInvalidDataType
  47. }
  48. // LoadFromFile loads the cedar from a file,
  49. // where dataType is either "json" or "gob".
  50. func (da *Cedar) LoadFromFile(fileName string, dataType string) error {
  51. file, err := os.OpenFile(fileName, os.O_RDONLY, 0600)
  52. defer file.Close()
  53. if err != nil {
  54. return err
  55. }
  56. in := bufio.NewReader(file)
  57. return da.Load(in, dataType)
  58. }