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. // GenerateUUID is used to generate a random UUID
  16. func GenerateUUID() (string, error) {
  17. buf, err := GenerateRandomBytes(16)
  18. if err != nil {
  19. return "", err
  20. }
  21. return FormatUUID(buf)
  22. }
  23. func FormatUUID(buf []byte) (string, error) {
  24. if len(buf) != 16 {
  25. return "", fmt.Errorf("wrong length byte slice (%d)", len(buf))
  26. }
  27. return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x",
  28. buf[0:4],
  29. buf[4:6],
  30. buf[6:8],
  31. buf[8:10],
  32. buf[10:16]), nil
  33. }
  34. func ParseUUID(uuid string) ([]byte, error) {
  35. if len(uuid) != 36 {
  36. return nil, fmt.Errorf("uuid string is wrong length")
  37. }
  38. hyph := []byte("-")
  39. if uuid[8] != hyph[0] ||
  40. uuid[13] != hyph[0] ||
  41. uuid[18] != hyph[0] ||
  42. uuid[23] != hyph[0] {
  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) != 16 {
  51. return nil, fmt.Errorf("decoded hex is the wrong length")
  52. }
  53. return ret, nil
  54. }