/
uuid.go
94 lines (82 loc) · 2.54 KB
/
uuid.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// @description make uuid, support short uuid
// @reference https://github.com/stochastic-technologies/shortuuid
// @authors Odin
package utils
import (
//"code.google.com/p/go-uuid/uuid"
"fmt"
"math/big"
"strings"
gouuid "github.com/nu7hatch/gouuid"
)
const (
alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
shortlen = 22 //这个长度是根据alphabet得来的,省略计算步骤
)
func ShortenUUID(s string) (ss string) {
//uuInt, tr, tm, off := new(big.Int), new(big.Int), new(big.Int), new(big.Int)
uuInt, off := new(big.Int), new(big.Int)
//remove "-"
s = strings.ToLower(strings.Replace(s, "-", "", -1))
//fmt.Sscan("0x"+s, uuInt)
uuInt.SetString(s, 16)
alphaLen := big.NewInt(int64(len(alphabet)))
for uuInt.Cmp(big.NewInt(0)) > 0 {
//uuInt, off = tr.DivMod(uuInt, alphaLen, tm)
uuInt, off = uuInt.DivMod(uuInt, alphaLen, off)
ss += string(alphabet[off.Int64()])
}
//如果不足22位,用第一个字符补全
if diff := shortlen - len(ss); diff > 0 {
ss += strings.Repeat(string(alphabet[0]), diff)
}
return
}
func LengthenUUID(s string) (ls string) {
uuInt, off := new(big.Int), new(big.Int)
alphaLen := big.NewInt(int64(len(alphabet)))
//需要倒序
for i := len(s) - 1; i >= 0; i-- {
char := s[i]
off = big.NewInt(int64(strings.Index(alphabet, string(char))))
uuInt = uuInt.Add(uuInt.Mul(uuInt, alphaLen), off)
}
//转为16进制
if b := fmt.Sprintf("%x", uuInt); b != "" {
//fmt.Println(b)
//b := []byte(b)
ll := len(b)
//考虑到前缀为零的情况. 倒过来,先满足后面的字符位数
ls = fmt.Sprintf("%08v-%04v-%04v-%04v-%012v",
b[:ll-24], b[ll-24:ll-20], b[ll-20:ll-16], b[ll-16:ll-12], b[ll-12:])
}
return
}
//default, version 4
func NewUUID() string {
//return uuid.New()
u4, _ := gouuid.NewV4()
return u4.String()
}
func NewShortUUID() string {
newUUID := NewUUID()
return ShortenUUID(newUUID)
}
// generate uuid v5
// namespace直接写域名或者url
func NewUUID5(namespace, data string) string {
//以http开头的为URL, 其余都为DNS
if strings.HasPrefix(strings.ToLower(namespace), "http") {
//return gouuid.NewV5(uuid.NameSpace_URL, []byte(namespace+data)).String()
u5, _ := gouuid.NewV5(gouuid.NamespaceURL, []byte(namespace+data))
return u5.String()
} else {
//return uuid.NewSHA1(uuid.NameSpace_DNS, []byte(namespace+data)).String()
u5, _ := gouuid.NewV5(gouuid.NamespaceDNS, []byte(namespace+data))
return u5.String()
}
}
func NewShortUUID5(namespace, data string) string {
newUUID := NewUUID5(namespace, data)
return ShortenUUID(newUUID)
}