一物一码
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.

1 年之前
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package utils
  2. import (
  3. "github.com/sony/sonyflake"
  4. "applet/app/utils/logx"
  5. "fmt"
  6. "math/rand"
  7. "time"
  8. )
  9. const (
  10. KC_RAND_KIND_NUM = 0 // 纯数字
  11. KC_RAND_KIND_LOWER = 1 // 小写字母
  12. KC_RAND_KIND_UPPER = 2 // 大写字母
  13. KC_RAND_KIND_ALL = 3 // 数字、大小写字母
  14. )
  15. func newUUID() *[16]byte {
  16. u := &[16]byte{}
  17. rand.Read(u[:16])
  18. u[8] = (u[8] | 0x80) & 0xBf
  19. u[6] = (u[6] | 0x40) & 0x4f
  20. return u
  21. }
  22. func UUIDString() string {
  23. u := newUUID()
  24. return fmt.Sprintf("%x-%x-%x-%x-%x", u[:4], u[4:6], u[6:8], u[8:10], u[10:])
  25. }
  26. func UUIDHexString() string {
  27. u := newUUID()
  28. return fmt.Sprintf("%x%x%x%x%x", u[:4], u[4:6], u[6:8], u[8:10], u[10:])
  29. }
  30. func UUIDBinString() string {
  31. u := newUUID()
  32. return fmt.Sprintf("%s", [16]byte(*u))
  33. }
  34. func Krand(size int, kind int) []byte {
  35. ikind, kinds, result := kind, [][]int{[]int{10, 48}, []int{26, 97}, []int{26, 65}}, make([]byte, size)
  36. isAll := kind > 2 || kind < 0
  37. rand.Seed(time.Now().UnixNano())
  38. for i := 0; i < size; i++ {
  39. if isAll { // random ikind
  40. ikind = rand.Intn(3)
  41. }
  42. scope, base := kinds[ikind][0], kinds[ikind][1]
  43. result[i] = uint8(base + rand.Intn(scope))
  44. }
  45. return result
  46. }
  47. // OrderUUID is only num for uuid
  48. func OrderUUID(uid int) string {
  49. ustr := IntToStr(uid)
  50. tstr := Int64ToStr(time.Now().Unix())
  51. ulen := len(ustr)
  52. tlen := len(tstr)
  53. rlen := 18 - ulen - tlen
  54. krb := Krand(rlen, KC_RAND_KIND_NUM)
  55. return ustr + tstr + string(krb)
  56. }
  57. var flake *sonyflake.Sonyflake
  58. func GenId() int64 {
  59. id, err := flake.NextID()
  60. if err != nil {
  61. _ = logx.Errorf("flake.NextID() failed with %s\n", err)
  62. panic(err)
  63. }
  64. return int64(id)
  65. }