uuid.go 1.1 KB

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