util.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. func FileExists(filename string) bool {
  15. stat, _ := os.Stat(filename)
  16. return stat != nil
  17. }
  18. // RandomString returns a random string with a given length
  19. func RandomString(length int) string {
  20. b := make([]byte, length)
  21. for i := range b {
  22. b[i] = randomStringCharset[random.Intn(len(randomStringCharset))]
  23. }
  24. return string(b)
  25. }
  26. // DurationToHuman converts a duration to a human readable format
  27. func DurationToHuman(d time.Duration) (str string) {
  28. if d == 0 {
  29. return "0"
  30. }
  31. d = d.Round(time.Second)
  32. days := d / time.Hour / 24
  33. if days > 0 {
  34. str += fmt.Sprintf("%dd", days)
  35. }
  36. d -= days * time.Hour * 24
  37. hours := d / time.Hour
  38. if hours > 0 {
  39. str += fmt.Sprintf("%dh", hours)
  40. }
  41. d -= hours * time.Hour
  42. minutes := d / time.Minute
  43. if minutes > 0 {
  44. str += fmt.Sprintf("%dm", minutes)
  45. }
  46. d -= minutes * time.Minute
  47. seconds := d / time.Second
  48. if seconds > 0 {
  49. str += fmt.Sprintf("%ds", seconds)
  50. }
  51. return
  52. }