-
Notifications
You must be signed in to change notification settings - Fork 129
/
id.go
65 lines (54 loc) · 1.15 KB
/
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
57
58
59
60
61
62
63
64
65
package idgen
import (
"crypto/rand"
"encoding/binary"
"github.com/dineshappavoo/basex"
"github.com/google/uuid"
"github.com/teris-io/shortid"
"math/big"
)
const Alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-"
var idGenerator Generator
func NewGenerator() Generator {
buf := make([]byte, 8)
_, _ = rand.Read(buf)
seed := binary.LittleEndian.Uint64(buf)
return &shortIdGenerator{
Shortid: shortid.MustNew(0, Alphabet, seed),
}
}
func init() {
idGenerator = NewGenerator()
}
func New() string {
id, _ := idGenerator.NextId()
return id
}
type Generator interface {
NextId() (string, error)
NextAlphaNumericPrefixedId() (string, error)
}
type shortIdGenerator struct {
*shortid.Shortid
}
func (self *shortIdGenerator) NextId() (string, error) {
return self.Generate()
}
func (self *shortIdGenerator) NextAlphaNumericPrefixedId() (string, error) {
for {
id, err := self.NextId()
if err != nil {
return "", err
}
if id[0] != '-' && id[0] != '.' {
return id, nil
}
}
}
func NewUUIDString() string {
id := uuid.New()
v := &big.Int{}
v.SetBytes(id[:])
result, _ := basex.EncodeInt(v)
return result
}