forked from unknwon/the-way-to-go_ZH_CN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
45 lines (38 loc) · 745 Bytes
/
store.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
package main
import "sync"
type URLStore struct {
urls map[string]string
mu sync.RWMutex
}
func NewURLStore() *URLStore {
return &URLStore{urls: make(map[string]string)}
}
func (s *URLStore) Get(key string) string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.urls[key]
}
func (s *URLStore) Set(key, url string) bool {
s.mu.Lock()
defer s.mu.Unlock()
if _, present := s.urls[key]; present {
return false
}
s.urls[key] = url
return true
}
func (s *URLStore) Count() int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.urls)
}
func (s *URLStore) Put(url string) string {
for {
key := genKey(s.Count()) // generate the short URL
if ok := s.Set(key, url); ok {
return key
}
}
// shouldn't get here
return ""
}