-
Notifications
You must be signed in to change notification settings - Fork 477
/
Copy pathid.go
56 lines (47 loc) · 956 Bytes
/
id.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
package seq
import (
"context"
"github.com/sony/sonyflake"
"google.golang.org/grpc/metadata"
"strconv"
"time"
)
var (
sf *sonyflake.Sonyflake
startTime = time.Date(2019, 7, 28, 0, 0, 0, 0, time.UTC)
)
func init() {
var st sonyflake.Settings
st.StartTime = startTime
sf = sonyflake.NewSonyflake(st)
if sf == nil {
panic("sonyflake not created")
}
}
func NextNumID() uint64 {
id, _ := sf.NextID()
return id
}
const IdPrefixKey = "p-id"
func NextID(ctx context.Context) string {
nextId, err := sf.NextID()
if err != nil {
return err.Error()
}
// uit64 转成 str
id := strconv.FormatUint(nextId, 10)
if ctx == nil {
ctx = context.Background()
}
if md, ok := metadata.FromIncomingContext(ctx); ok {
if ps := md.Get(IdPrefixKey); len(ps) != 0 {
return ps[0] + id
}
}
if md, ok := metadata.FromOutgoingContext(ctx); ok {
if ps := md.Get(IdPrefixKey); len(ps) != 0 {
return ps[0] + id
}
}
return id
}