util.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package util
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "os"
  6. "time"
  7. )
  8. const (
  9. randomStringCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  10. )
  11. var (
  12. random = rand.New(rand.NewSource(time.Now().UnixNano()))
  13. )
  14. // FileExists checks if a file exists, and returns true if it does
  15. func FileExists(filename string) bool {
  16. stat, _ := os.Stat(filename)
  17. return stat != nil
  18. }
  19. // RandomString returns a random string with a given length
  20. func RandomString(length int) string {
  21. b := make([]byte, length)
  22. for i := range b {
  23. b[i] = randomStringCharset[random.Intn(len(randomStringCharset))]
  24. }
  25. return string(b)
  26. }
  27. // DurationToHuman converts a duration to a human readable format
  28. func DurationToHuman(d time.Duration) (str string) {
  29. if d == 0 {
  30. return "0"
  31. }
  32. d = d.Round(time.Second)
  33. days := d / time.Hour / 24
  34. if days > 0 {
  35. str += fmt.Sprintf("%dd", days)
  36. }
  37. d -= days * time.Hour * 24
  38. hours := d / time.Hour
  39. if hours > 0 {
  40. str += fmt.Sprintf("%dh", hours)
  41. }
  42. d -= hours * time.Hour
  43. minutes := d / time.Minute
  44. if minutes > 0 {
  45. str += fmt.Sprintf("%dm", minutes)
  46. }
  47. d -= minutes * time.Minute
  48. seconds := d / time.Second
  49. if seconds > 0 {
  50. str += fmt.Sprintf("%ds", seconds)
  51. }
  52. return
  53. }