uuid.go 1.3 KB

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