-
Notifications
You must be signed in to change notification settings - Fork 0
/
sid.go
59 lines (49 loc) · 1.03 KB
/
sid.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
package helpers
import (
"fmt"
"github.com/pkg/errors"
"github.com/sony/sonyflake"
)
const (
base62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
type Sid struct {
sf *sonyflake.Sonyflake
}
func NewSid() *Sid {
sf := sonyflake.NewSonyflake(sonyflake.Settings{})
if sf == nil {
panic("sonyflake not created")
}
return &Sid{sf}
}
func (s Sid) GenString() (string, error) {
// 生成分布式ID
id, err := s.sf.NextID()
if err != nil {
return "", errors.Wrap(err, "failed to generate sonyflake ID")
}
// 将ID转换为字符串
return IntToBase62(int(id)), nil
}
func (s Sid) GenUint64() (uint64, error) {
// 生成分布式ID
return s.sf.NextID()
}
func IntToBase62(n int) string {
if n == 0 {
return string(base62[0])
}
var result []byte
for n > 0 {
result = append(result, base62[n%62])
n /= 62
fmt.Println(n)
}
// 反转字符串
for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
result[i], result[j] = result[j], result[i]
fmt.Println(result)
}
return string(result)
}