file_operations.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package utils
  2. import (
  3. "os"
  4. "path/filepath"
  5. "reflect"
  6. "strings"
  7. )
  8. //@author: [songzhibin97](https://github.com/songzhibin97)
  9. //@function: FileMove
  10. //@description: 文件移动供外部调用
  11. //@param: src string, dst string(src: 源位置,绝对路径or相对路径, dst: 目标位置,绝对路径or相对路径,必须为文件夹)
  12. //@return: err error
  13. func FileMove(src string, dst string) (err error) {
  14. if dst == "" {
  15. return nil
  16. }
  17. src, err = filepath.Abs(src)
  18. if err != nil {
  19. return err
  20. }
  21. dst, err = filepath.Abs(dst)
  22. if err != nil {
  23. return err
  24. }
  25. var revoke = false
  26. dir := filepath.Dir(dst)
  27. Redirect:
  28. _, err = os.Stat(dir)
  29. if err != nil {
  30. err = os.MkdirAll(dir, 0755)
  31. if err != nil {
  32. return err
  33. }
  34. if !revoke {
  35. revoke = true
  36. goto Redirect
  37. }
  38. }
  39. return os.Rename(src, dst)
  40. }
  41. func DeLFile(filePath string) error {
  42. return os.RemoveAll(filePath)
  43. }
  44. //@author: [songzhibin97](https://github.com/songzhibin97)
  45. //@function: TrimSpace
  46. //@description: 去除结构体空格
  47. //@param: target interface (target: 目标结构体,传入必须是指针类型)
  48. //@return: null
  49. func TrimSpace(target interface{}) {
  50. t := reflect.TypeOf(target)
  51. if t.Kind() != reflect.Ptr {
  52. return
  53. }
  54. t = t.Elem()
  55. v := reflect.ValueOf(target).Elem()
  56. for i := 0; i < t.NumField(); i++ {
  57. switch v.Field(i).Kind() {
  58. case reflect.String:
  59. v.Field(i).SetString(strings.TrimSpace(v.Field(i).String()))
  60. }
  61. }
  62. return
  63. }