file.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package store
  2. import (
  3. "context"
  4. "io/ioutil"
  5. "os"
  6. "path"
  7. "go-common/library/log"
  8. "github.com/pkg/errors"
  9. )
  10. // FileConfig config of File.
  11. type FileConfig struct {
  12. RootDir string
  13. }
  14. // File is a degrade file service.
  15. type File struct {
  16. c *FileConfig
  17. }
  18. var _ Store = &File{}
  19. // NewFile new a file degrade service.
  20. func NewFile(fc *FileConfig) *File {
  21. if fc == nil {
  22. panic(errors.New("file config is nil"))
  23. }
  24. fs := &File{c: fc}
  25. if err := os.MkdirAll(fs.c.RootDir, 0755); err != nil {
  26. panic(errors.Wrapf(err, "dir: %s", fs.c.RootDir))
  27. }
  28. return fs
  29. }
  30. // Set save the result of location to file.
  31. // expire is not implemented in file storage.
  32. func (fs *File) Set(ctx context.Context, key string, bs []byte, _ int32) (err error) {
  33. file := path.Join(fs.c.RootDir, key)
  34. tmp := file + ".tmp"
  35. if err = ioutil.WriteFile(tmp, bs, 0644); err != nil {
  36. log.Error("ioutil.WriteFile(%s, bs, 0644): error(%v)", tmp, err)
  37. err = errors.Wrapf(err, "key: %s", key)
  38. return
  39. }
  40. if err = os.Rename(tmp, file); err != nil {
  41. log.Error("os.Rename(%s, %s): error(%v)", tmp, file, err)
  42. err = errors.Wrapf(err, "key: %s", key)
  43. return
  44. }
  45. return
  46. }
  47. // Get get result from file by locaiton+params.
  48. func (fs *File) Get(ctx context.Context, key string) (bs []byte, err error) {
  49. p := path.Join(fs.c.RootDir, key)
  50. if bs, err = ioutil.ReadFile(p); err != nil {
  51. log.Error("ioutil.ReadFile(%s): error(%v)", p, err)
  52. err = errors.Wrapf(err, "key: %s", key)
  53. return
  54. }
  55. return
  56. }