-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
93 lines (77 loc) · 1.76 KB
/
util.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
package main
import (
"crypto/md5"
"encoding/hex"
"os"
"strconv"
"sync"
"time"
"github.com/go-zookeeper/zk"
)
var (
// CharacterSet consists of 62 characters [0-9][A-Z][a-z].
Base = 62
CharacterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
)
var LENGTH int = 7
var URL = os.Getenv("ZOOKEEPER_URL")
var zookeeperPath = "/seed"
var zookeeper *zk.Conn
var counterRange int = 100
var counterNow int = 0
var counterBase int
var counterNowLock sync.Mutex
func InitZookeeper() {
c, _, err := zk.Connect([]string{URL}, time.Second) //*10)
zookeeper = c
if err != nil {
panic(err)
}
// zookeeper register
data := []byte("0")
zookeeper.Create(zookeeperPath, data, 0, zk.WorldACL(zk.PermAll))
counterBase = getCounter()
}
func GenerateShortName(longURL string) string {
shortName := getUniqueShortName()
UpdateCounterBase()
return shortName
}
func getUniqueShortName() string {
counter := getCounter()
hash := md5.Sum([]byte(strconv.Itoa(counter)))
candidateName := hex.EncodeToString(hash[:])
i := 0
// TODO: maybe can do better
// check collision
for {
if !db.ShortNameExist(candidateName[i : i+LENGTH]) {
break
}
i += 1
}
return candidateName[i : i+LENGTH]
}
func getCounter() int {
counterNowLock.Lock()
counter := counterNow + counterBase*counterRange
counterNow += 1
counterNowLock.Unlock()
return counter
}
func UpdateCounterBase() {
if counterNow == counterRange {
counterNow = 0
counterBase = getNewCounterBase()
}
}
func getNewCounterBase() int {
// get the counter number
counterByteArray, _, err := zookeeper.Get(zookeeperPath)
if err != nil {
panic(err)
}
counter, _ := strconv.Atoi(string(counterByteArray))
zookeeper.Set(zookeeperPath, []byte(strconv.Itoa(counter+1)), -1)
return counter
}