常用类型及数据操作方法
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.

71 lines
1.4 KiB

3 years ago
  1. package helper
  2. import (
  3. "crypto/rand"
  4. "encoding/hex"
  5. "fmt"
  6. )
  7. // Simple call
  8. func NewUUID() string {
  9. uuid, _ := GenerateUUID()
  10. return uuid
  11. }
  12. // GenerateRandomBytes is used to generate random bytes of given size.
  13. func GenerateRandomBytes(size int) ([]byte, error) {
  14. buf := make([]byte, size)
  15. if _, err := rand.Read(buf); err != nil {
  16. return nil, fmt.Errorf("failed to read random bytes: %v", err)
  17. }
  18. return buf, nil
  19. }
  20. const uuidLen = 16
  21. // GenerateUUID is used to generate a random UUID
  22. func GenerateUUID() (string, error) {
  23. buf, err := GenerateRandomBytes(uuidLen)
  24. if err != nil {
  25. return "", err
  26. }
  27. return FormatUUID(buf)
  28. }
  29. func FormatUUID(buf []byte) (string, error) {
  30. if buflen := len(buf); buflen != uuidLen {
  31. return "", fmt.Errorf("wrong length byte slice (%d)", buflen)
  32. }
  33. return fmt.Sprintf("%x-%x-%x-%x-%x",
  34. buf[0:4],
  35. buf[4:6],
  36. buf[6:8],
  37. buf[8:10],
  38. buf[10:16]), nil
  39. }
  40. func ParseUUID(uuid string) ([]byte, error) {
  41. if len(uuid) != 2*uuidLen+4 {
  42. return nil, fmt.Errorf("uuid string is wrong length")
  43. }
  44. if uuid[8] != '-' ||
  45. uuid[13] != '-' ||
  46. uuid[18] != '-' ||
  47. uuid[23] != '-' {
  48. return nil, fmt.Errorf("uuid is improperly formatted")
  49. }
  50. hexStr := uuid[0:8] + uuid[9:13] + uuid[14:18] + uuid[19:23] + uuid[24:36]
  51. ret, err := hex.DecodeString(hexStr)
  52. if err != nil {
  53. return nil, err
  54. }
  55. if len(ret) != uuidLen {
  56. return nil, fmt.Errorf("decoded hex is the wrong length")
  57. }
  58. return ret, nil
  59. }