libString.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package lib
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "math/rand"
  6. "strconv"
  7. "strings"
  8. "time"
  9. )
  10. // #取得随机字符串:通过打乱slice来操作
  11. func GetRandstring(length int, char string, rand_x int64) string {
  12. if length < 1 {
  13. return ""
  14. }
  15. if len(char) <= 6 || len(char) <= length {
  16. char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  17. }
  18. charArr := strings.Split(char, "")
  19. ran := rand.New(rand.NewSource(time.Now().Unix() + rand_x))
  20. l := len(charArr)
  21. for i := l - 1; i > 0; i-- {
  22. r := ran.Intn(i)
  23. charArr[r], charArr[i] = charArr[i], charArr[r]
  24. }
  25. rchar := charArr[:length]
  26. return strings.Join(rchar, "")
  27. }
  28. // 返回一个32位md5加密后的字符串
  29. func Md5(str string) string {
  30. h := md5.New()
  31. h.Write([]byte(str))
  32. return hex.EncodeToString(h.Sum(nil))
  33. }
  34. // 转化
  35. func TimeStrToTime(T_time string) (time.Time, bool) {
  36. stamp, err := time.Parse("2006-01-02 15:04:05", T_time)
  37. if err != nil {
  38. return time.Time{}, false
  39. }
  40. return stamp, true
  41. }
  42. func SplitStringIds(str string, prefix string) (r []string) {
  43. Ids_str := strings.TrimRight(str, "|")
  44. Ids := strings.Split(Ids_str, "|")
  45. for _, v := range Ids {
  46. r = append(r, strings.TrimLeft(v, prefix))
  47. }
  48. return r
  49. }
  50. func SplitStringToDotStr(str string, prefix string) (r string) {
  51. Ids_str := strings.TrimRight(str, "|")
  52. Ids := strings.Split(Ids_str, "|")
  53. for _, v := range Ids {
  54. r += strings.TrimLeft(v, prefix) + ","
  55. }
  56. r = strings.TrimRight(r, ",")
  57. return r
  58. }
  59. func SplitStringToIntIds(str string, prefix string) (r []int) {
  60. Ids_str := strings.TrimRight(str, "|")
  61. Ids := strings.Split(Ids_str, "|")
  62. for _, v := range Ids {
  63. id, _ := strconv.Atoi(strings.TrimLeft(v, prefix))
  64. r = append(r, id)
  65. }
  66. return r
  67. }
  68. func IntIdsDistinct(Ids []int) (result []int) {
  69. distinctMap := make(map[int]int, len(Ids))
  70. for _, Id := range Ids {
  71. if _, ok := distinctMap[Id]; !ok {
  72. distinctMap[Id] = 1
  73. result = append(result, Id)
  74. }
  75. }
  76. return result
  77. }