util.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package util
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "os"
  6. "sync"
  7. "time"
  8. )
  9. const (
  10. randomStringCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  11. )
  12. var (
  13. random = rand.New(rand.NewSource(time.Now().UnixNano()))
  14. randomMutex = sync.Mutex{}
  15. )
  16. // FileExists checks if a file exists, and returns true if it does
  17. func FileExists(filename string) bool {
  18. stat, _ := os.Stat(filename)
  19. return stat != nil
  20. }
  21. // InStringList returns true if needle is contained in haystack
  22. func InStringList(haystack []string, needle string) bool {
  23. for _, s := range haystack {
  24. if s == needle {
  25. return true
  26. }
  27. }
  28. return false
  29. }
  30. // RandomString returns a random string with a given length
  31. func RandomString(length int) string {
  32. randomMutex.Lock() // Who would have thought that random.Intn() is not thread-safe?!
  33. defer randomMutex.Unlock()
  34. b := make([]byte, length)
  35. for i := range b {
  36. b[i] = randomStringCharset[random.Intn(len(randomStringCharset))]
  37. }
  38. return string(b)
  39. }
  40. // DurationToHuman converts a duration to a human readable format
  41. func DurationToHuman(d time.Duration) (str string) {
  42. if d == 0 {
  43. return "0"
  44. }
  45. d = d.Round(time.Second)
  46. days := d / time.Hour / 24
  47. if days > 0 {
  48. str += fmt.Sprintf("%dd", days)
  49. }
  50. d -= days * time.Hour * 24
  51. hours := d / time.Hour
  52. if hours > 0 {
  53. str += fmt.Sprintf("%dh", hours)
  54. }
  55. d -= hours * time.Hour
  56. minutes := d / time.Minute
  57. if minutes > 0 {
  58. str += fmt.Sprintf("%dm", minutes)
  59. }
  60. d -= minutes * time.Minute
  61. seconds := d / time.Second
  62. if seconds > 0 {
  63. str += fmt.Sprintf("%ds", seconds)
  64. }
  65. return
  66. }