You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
783 B

  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "os"
  7. )
  8. func loadFromReader(r io.Reader, obj interface{}) error {
  9. buf := new(bytes.Buffer)
  10. if _, err := buf.ReadFrom(r); err != nil {
  11. return err
  12. }
  13. return json.Unmarshal(buf.Bytes(), obj)
  14. }
  15. func loadFromFile(path string, obj interface{}) error {
  16. f, err := os.Open(path)
  17. if err != nil {
  18. return err
  19. }
  20. defer f.Close()
  21. return loadFromReader(f, obj)
  22. }
  23. func saveToWriter(w io.Writer, obj interface{}) error {
  24. b, err := json.MarshalIndent(obj, "", " ")
  25. if err != nil {
  26. return err
  27. }
  28. if _, err := w.Write(b); err != nil {
  29. return err
  30. }
  31. return nil
  32. }
  33. func saveToFile(path string, obj interface{}) error {
  34. f, err := os.Create(path)
  35. if err != nil {
  36. return err
  37. }
  38. defer f.Close()
  39. return saveToWriter(f, obj)
  40. }