Created
April 21, 2017 16:32
-
-
Save rkravchik/d9733e1d2d626188eb91df751471d739 to your computer and use it in GitHub Desktop.
Generate UUID without additional dependencies. Only crypto/rand.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// newUUID generates a random UUID according to RFC 4122 | |
func newUUID() (string, error) { | |
uuid := make([]byte, 16) | |
n, err := io.ReadFull(rand.Reader, uuid) | |
if n != len(uuid) || err != nil { | |
return "", err | |
} | |
// variant bits; see section 4.1.1 | |
uuid[8] = uuid[8]&^0xc0 | 0x80 | |
// version 4 (pseudo-random); see section 4.1.3 | |
uuid[6] = uuid[6]&^0xf0 | 0x40 | |
return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment