You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.3KB

  1. package goutil
  2. import (
  3. "errors"
  4. "io"
  5. "math"
  6. "os"
  7. "regexp"
  8. "time"
  9. "github.com/hako/durafmt"
  10. )
  11. func FilterToAlnum(input string) string {
  12. re := regexp.MustCompile("[^a-zA-Z0-9]+")
  13. return re.ReplaceAllString(input, "")
  14. }
  15. func TimeDiffHuman(first time.Time, second time.Time) string {
  16. if first.Before(second) {
  17. return durafmt.ParseShort(second.Sub(first)).String()
  18. } else {
  19. return durafmt.ParseShort(first.Sub(second)).String()
  20. }
  21. }
  22. // Does anyone else use uints for things that are always >=0 like counts and
  23. func TimeDiffAbsSeconds(first time.Time, second time.Time) uint {
  24. return uint(math.Abs(first.Sub(second).Truncate(time.Second).Seconds()))
  25. }
  26. func Mkdirp(p string) error {
  27. src, err := os.Stat(p)
  28. if os.IsNotExist(err) {
  29. errDir := os.MkdirAll(p, 0755)
  30. if errDir != nil {
  31. return errDir
  32. }
  33. return nil
  34. }
  35. if src.Mode().IsRegular() {
  36. return errors.New("file already exists at path")
  37. }
  38. return nil
  39. }
  40. // straight outta stackoverflow
  41. // https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
  42. func CopyFile(src, dst string) (err error) {
  43. in, err := os.Open(src)
  44. if err != nil {
  45. return
  46. }
  47. defer in.Close()
  48. out, err := os.Create(dst)
  49. if err != nil {
  50. return
  51. }
  52. defer func() {
  53. cerr := out.Close()
  54. if err == nil {
  55. err = cerr
  56. }
  57. }()
  58. if _, err = io.Copy(out, in); err != nil {
  59. return
  60. }
  61. err = out.Sync()
  62. return
  63. }
  64. const milliInSecond int64 = 1000
  65. const microInSecond int64 = 1000000
  66. const nsInSecond int64 = 1000000000
  67. func TimeFromUnixMilli(input int64) time.Time {
  68. var wholeSeconds int64 = input / milliInSecond
  69. var remainderMillis int64 = input - (wholeSeconds * milliInSecond)
  70. var remainderNano int64 = remainderMillis * 1000000
  71. return time.Unix(wholeSeconds, remainderNano)
  72. }
  73. func TimeFromUnixMicro(input int64) time.Time {
  74. var wholeSeconds int64 = input / microInSecond
  75. var remainderMicros int64 = input - (wholeSeconds * microInSecond)
  76. var remainderNano int64 = remainderMicros * 1000
  77. return time.Unix(wholeSeconds, remainderNano)
  78. }
  79. func TimeFromWebKit(input int64) time.Time {
  80. // webkit time is stupid and uses 1601-01-01 for epoch
  81. // it's 11644473600 seconds behind unix 1970-01-01 epoch
  82. // it's also in microseconds
  83. unixMicrosCorrected := input - (11644473600 * 1000000)
  84. return TimeFromUnixMicro(unixMicrosCorrected)
  85. }