1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-10 15:52:27 +08:00

feat: add func UUIdV4

This commit is contained in:
dudaodong
2022-02-20 10:16:15 +08:00
parent 96d57a6d24
commit a19a861552
2 changed files with 29 additions and 0 deletions

View File

@@ -6,6 +6,7 @@ package random
import (
crand "crypto/rand"
"fmt"
"io"
"math/rand"
"time"
@@ -48,3 +49,18 @@ func RandBytes(length int) []byte {
}
return b
}
// UUIdV4 generate a random UUID of version 4 according to RFC 4122
func UUIdV4() (string, error) {
uuid := make([]byte, 16)
n, err := io.ReadFull(crand.Reader, uuid)
if n != len(uuid) || err != nil {
return "", err
}
uuid[8] = uuid[8]&^0xc0 | 0x80
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
}