-
Notifications
You must be signed in to change notification settings - Fork 0
/
shard.go
76 lines (63 loc) · 1.55 KB
/
shard.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
package i18n
import (
"crypto/sha1"
"encoding/binary"
"fmt"
"net/http"
"sync"
"unsafe"
"golang.org/x/text/language"
)
func shardGenerate(r *http.Request) string {
uintVal := uint64(uintptr(unsafe.Pointer(r)))
hasher := sha1.New()
binary.Write(hasher, binary.LittleEndian, uintVal)
return fmt.Sprintf("%x", hasher.Sum(nil))[0:2]
}
type requestShard struct {
lock sync.RWMutex
data map[*http.Request]language.Tag
}
type requestLanguageMap struct {
lock sync.RWMutex
data map[string]*requestShard
}
func newRequestLanguageMap() *requestLanguageMap {
return &requestLanguageMap{
data: make(map[string]*requestShard),
}
}
func (rMap *requestLanguageMap) getShard(request *http.Request) *requestShard {
key := shardGenerate(request)
rMap.lock.RLock()
shard, ok := rMap.data[key]
rMap.lock.RUnlock()
if !ok || shard == nil {
rMap.lock.Lock()
shard = &requestShard{
data: make(map[*http.Request]language.Tag),
}
rMap.data[key] = shard
rMap.lock.Unlock()
}
return shard
}
func (rMap *requestLanguageMap) Add(request *http.Request, tag language.Tag) {
shard := rMap.getShard(request)
shard.lock.Lock()
defer shard.lock.Unlock()
shard.data[request] = tag
}
func (rMap *requestLanguageMap) Delete(request *http.Request) {
shard := rMap.getShard(request)
shard.lock.Lock()
defer shard.lock.Unlock()
delete(shard.data, request)
}
func (rMap *requestLanguageMap) Get(request *http.Request) (language.Tag, bool) {
shard := rMap.getShard(request)
shard.lock.Lock()
defer shard.lock.Unlock()
lang, ok := shard.data[request]
return lang, ok
}