-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
111 lines (100 loc) · 2.04 KB
/
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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
// "bufio"
"encoding/gob"
"io"
"log"
"os"
"sync"
)
const saveQueueLength = 1000
type URLStore struct {
urls map[string]string
mu sync.RWMutex
save chan record
}
type record struct {
Key, URL string
}
func NewURLStore(filename string) *URLStore {
s := &URLStore{
urls: make(map[string]string),
save: make(chan record, saveQueueLength),
}
if err := s.load(filename); err != nil {
log.Println("Error loading URLStore:", err)
}
go s.saveLoop(filename)
return s
}
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())
if ok := s.Set(key, url); ok {
s.save <- record{key, url}
return key
}
}
panic("shouldn't get here")
}
func (s *URLStore) load(filename string) error {
f, err := os.Open(filename)
if err != nil {
log.Println("Error opening URLStore:", err)
return err
}
defer f.Close()
// buffered reading:
// b := bufio.NewReader(f)
// d := gob.NewDecoder(b)
d := gob.NewDecoder(f)
for err == nil {
var r record
if err = d.Decode(&r); err == nil {
s.Set(r.Key, r.URL)
}
}
if err == io.EOF {
return nil
}
// error occurred:
log.Println("Error decoding URLStore:", err) // map hasn't been read correctly
return err
}
func (s *URLStore) saveLoop(filename string) {
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatal("Error opening URLStore: ", err)
}
defer f.Close()
e := gob.NewEncoder(f)
// buffered encoding:
// b := bufio.NewWriter(f)
// e := gob.NewEncoder(b)
// defer b.Flush()
for {
r := <-s.save // takes a record from the channel
if err := e.Encode(r); err != nil {
log.Println("Error saving to URLStore: ", err)
}
}
}