-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.go
57 lines (43 loc) · 915 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
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"encoding/json"
"os"
)
const storeFile = "urls.json"
type URLStore struct {
Urls map[string]string
}
func NewURLStore() (*URLStore, error) {
store := &URLStore{Urls: make(map[string]string)}
if err := store.load(); err != nil {
return nil, err
}
return store, nil
}
func (s *URLStore) load() error {
file, err := os.Open(storeFile)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
defer file.Close()
return json.NewDecoder(file).Decode(&s.Urls)
}
func (s *URLStore) save() error {
file, err := os.Create(storeFile)
if err != nil {
return err
}
defer file.Close()
return json.NewEncoder(file).Encode(s.Urls)
}
func (s *URLStore) SaveUrl(shortUrl, longUrl string) {
s.Urls[shortUrl] = longUrl
s.save()
}
func (s *URLStore) GetUrl(shortUrl string) (string, bool) {
longUrls, exists := s.Urls[shortUrl]
return longUrls, exists
}