file.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package utils
  2. import (
  3. "strings"
  4. "os"
  5. "fmt"
  6. "path/filepath"
  7. "io"
  8. "math"
  9. )
  10. func AbsolutePath(p string) (string,error) {
  11. if strings.HasPrefix(p, "~") {
  12. home := os.Getenv("HOME")
  13. if home == "" {
  14. panic(fmt.Sprintf("can not found HOME in envs, '%s' AbsPh Failed!", p))
  15. }
  16. p = fmt.Sprint(home, string(p[1:]))
  17. }
  18. s, err := filepath.Abs(p)
  19. if nil != err {
  20. return "",err
  21. }
  22. return s,nil
  23. }
  24. // FileExists reports whether the named file or directory exists.
  25. func FileExists(name string) bool {
  26. if _, err := os.Stat(name); err != nil {
  27. if os.IsNotExist(err) {
  28. return false
  29. }
  30. }
  31. return true
  32. }
  33. func CopyFile(dstName, srcName string) (written int64, err error) {
  34. src, err := os.Open(srcName)
  35. if err != nil {
  36. return
  37. }
  38. defer src.Close()
  39. dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
  40. if err != nil {
  41. return
  42. }
  43. defer dst.Close()
  44. return io.Copy(dst, src)
  45. }
  46. func FormatBytes(size int64) string {
  47. units := []string{" B", " KB", " MB", " GB", " TB"}
  48. s := float64(size)
  49. i := 0
  50. for ; s >= 1024 && i < 4 ; i ++ {
  51. s /= 1024
  52. }
  53. return fmt.Sprintf("%.2f%s",s,units[i])
  54. }
  55. func Round(val float64, places int) float64 {
  56. var t float64
  57. f := math.Pow10(places)
  58. x := val * f
  59. if math.IsInf(x, 0) || math.IsNaN(x) {
  60. return val
  61. }
  62. if x >= 0.0 {
  63. t = math.Ceil(x)
  64. if (t - x) > 0.50000000001 {
  65. t -= 1.0
  66. }
  67. } else {
  68. t = math.Ceil(-x)
  69. if (t + x) > 0.50000000001 {
  70. t -= 1.0
  71. }
  72. t = -t
  73. }
  74. x = t / f
  75. if !math.IsInf(x, 0) {
  76. return x
  77. }
  78. return t
  79. }