fileaccess.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "regexp"
  8. "sparrow/pkg/rpcs"
  9. "sparrow/pkg/server"
  10. "sparrow/pkg/utils"
  11. "sync"
  12. )
  13. // FileAccess RPC服务
  14. type FileAccess struct {
  15. mu sync.RWMutex
  16. }
  17. // NewFileAccess create a FileAccessor instance
  18. func NewFileAccess() *FileAccess {
  19. return &FileAccess{}
  20. }
  21. // MoveFile move a file to new path
  22. // source:http://192.168.175.60:9000/upload/tmp/2c9d7d85-2266-450a-9d47-28e67703d818.jpeg
  23. func (f *FileAccess) MoveFile(args *rpcs.ArgsMoveFile, reply *rpcs.ReplyMoveFile) error {
  24. // check source file
  25. reg := regexp.MustCompile(`tmp/\$*.*`)
  26. src := reg.FindString(args.Source)
  27. fileName := filepath.Base(src)
  28. server.Log.Debug(src)
  29. src = *conStaticPath + "/" + src
  30. b, err := utils.Exists(src)
  31. if err != nil {
  32. server.Log.Error(err)
  33. return err
  34. }
  35. if b {
  36. // copy file
  37. sourceFileStat, err := os.Stat(src)
  38. if err != nil {
  39. return err
  40. }
  41. if !sourceFileStat.Mode().IsRegular() {
  42. return fmt.Errorf("%s is not a regular file", src)
  43. }
  44. source, err := os.Open(src)
  45. if err != nil {
  46. return err
  47. }
  48. defer source.Close()
  49. dst := *conStaticPath + "/" + args.Target + "/" + fileName
  50. utils.CreateIfNotExist(dst)
  51. destination, err := os.Create(dst)
  52. if err != nil {
  53. return err
  54. }
  55. defer destination.Close()
  56. io.Copy(destination, source)
  57. fpath := fmt.Sprintf("http://%s/%s/%s/%s", server.GetHTTPHost(), *conStaticPath, args.Target, fileName)
  58. if *conDomain != "" {
  59. fpath = fmt.Sprintf("http://%s/%s/%s/%s", *conDomain, *conStaticPath, args.Target, fileName)
  60. }
  61. reply.FilePath = fpath
  62. //delete src
  63. os.Remove(src)
  64. return nil
  65. }
  66. return nil
  67. }