-
Notifications
You must be signed in to change notification settings - Fork 0
/
snowflake.go
79 lines (67 loc) · 1.66 KB
/
snowflake.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package gotils
import (
"errors"
"fmt"
"log"
"regexp"
"strings"
"sync/atomic"
"time"
)
var ErrorInvalidId = errors.New("invalid Snowflake ID")
var snowflakeMonoCount = uint32(0)
var snowflakeMachineID = PrivateIPV4GetLower32OrDie()
var reOnlyChars *regexp.Regexp = regexp.MustCompile(`[a-zA-Z0-9]+`)
func SnowflakeID(idType string, nowLocal time.Time) string {
uniqueID := ""
nowUTC := nowLocal.UTC()
if reOnlyChars.MatchString(idType) {
var uniqueC = (atomic.AddUint32(&snowflakeMonoCount, 1)) % 0xFFFF
uniqueID = fmt.Sprintf("%s_%04d%02d%02d%02d%02d%02d_%08x%04x",
idType,
nowUTC.Year(),
nowUTC.Month(),
nowUTC.Day(),
nowUTC.Hour(),
nowUTC.Minute(),
nowUTC.Second(),
snowflakeMachineID,
uniqueC)
} else {
log.Fatalln("Invalid ID:", idType)
CheckFatal(ErrorInvalidId)
}
return uniqueID
}
func SnowflakeIDWithGroup(idType string, nowLocal time.Time) (groupID string, uniqueID string) {
nowUTC := nowLocal.UTC()
if reOnlyChars.MatchString(idType) {
var uniqueC = (atomic.AddUint32(&snowflakeMonoCount, 1)) % 0xFFFF
groupID = fmt.Sprintf("%04d%02d%02d",
nowUTC.Year(),
nowUTC.Month(),
nowUTC.Day())
uniqueID = fmt.Sprintf("%s_%04d%02d%02d%02d%02d%02d_%08x%04x",
idType,
nowUTC.Year(),
nowUTC.Month(),
nowUTC.Day(),
nowUTC.Hour(),
nowUTC.Minute(),
nowUTC.Second(),
snowflakeMachineID,
uniqueC)
} else {
log.Fatalln("Invalid ID:", idType)
CheckFatal(ErrorInvalidId)
}
return groupID, uniqueID
}
func SnowflakeExtractGroup(id string, idType string) string {
groupID := ""
components := strings.Split(id, idType)
if len(components) > 1 {
groupID = components[1][1:9]
}
return groupID
}