file.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package v1
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "os"
  6. "path"
  7. "go-common/app/infra/config/model"
  8. "go-common/library/log"
  9. )
  10. // SetFile set config file.
  11. func (d *Dao) SetFile(name string, conf *model.Content) (err error) {
  12. b, err := json.Marshal(conf)
  13. if err != nil {
  14. log.Error("json.Marshal(%v) error(%v)", conf, err)
  15. return
  16. }
  17. p := path.Join(d.pathCache, name)
  18. if err = ioutil.WriteFile(p, b, 0644); err != nil {
  19. log.Error("ioutil.WriteFile(%s) error(%v)", p, err)
  20. }
  21. return
  22. }
  23. // File return config file.
  24. func (d *Dao) File(name string) (res *model.Content, err error) {
  25. p := path.Join(d.pathCache, name)
  26. b, err := ioutil.ReadFile(p)
  27. if err != nil {
  28. log.Error("ioutil.ReadFile(%s) error(%v)", p, err)
  29. return
  30. }
  31. res = &model.Content{}
  32. if err = json.Unmarshal(b, &res); err != nil {
  33. log.Error("json.Unmarshal(%s) error(%v)", b, err)
  34. }
  35. return
  36. }
  37. // DelFile delete file cache.
  38. func (d *Dao) DelFile(name string) (err error) {
  39. p := path.Join(d.pathCache, name)
  40. if err = os.Remove(p); err != nil {
  41. log.Error("os.Remove(%s) error(%v)", p, err)
  42. }
  43. return
  44. }
  45. // SetFileStr save string file.
  46. func (d *Dao) SetFileStr(name string, val string) (err error) {
  47. p := path.Join(d.pathCache, name)
  48. if err = ioutil.WriteFile(p, []byte(val), 0644); err != nil {
  49. log.Error("ioutil.WriteFile(%s) error(%v)", p, err)
  50. }
  51. return
  52. }
  53. // FileStr get string file.
  54. func (d *Dao) FileStr(name string) (file string, err error) {
  55. p := path.Join(d.pathCache, name)
  56. b, err := ioutil.ReadFile(p)
  57. if err != nil {
  58. log.Error("ioutil.ReadFile(%s) error(%v)", p, err)
  59. return
  60. }
  61. file = string(b)
  62. return
  63. }