/
shortener.go
144 lines (125 loc) · 2.85 KB
/
shortener.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package shortener
import (
"crypto/sha1"
"encoding/base64"
"encoding/gob"
"fmt"
gocache "github.com/patrickmn/go-cache"
"net/url"
"os"
"regexp"
"strings"
"sync"
"time"
)
type address struct {
Url string
Clicks int64
}
type Cat struct {
age int
name string
friends []string
}
func Add(longUrl string, cache *gocache.Cache) (string, bool) {
if longUrl == "" {
return "", false
}
if !isValidUrl(longUrl) {
longUrl = "http://" + longUrl
}
if !isValidUrl(longUrl) {
return "", false
}
hasher := sha1.New()
hasher.Write([]byte(longUrl + time.Now().String()))
sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
sha = strings.ToUpper(sha)
key := url.PathEscape(sha)
index := 5
for {
if !(isExist(key[:index], cache)) {
break
}
index++
if index == len(key) {
hasher.Write([]byte(longUrl + time.Now().String()))
sha = base64.URLEncoding.EncodeToString(hasher.Sum(nil))
sha = strings.ToUpper(sha)
key += url.PathEscape(sha)
}
}
err := cache.Add(key[:index], address{Url: longUrl, Clicks: 0}, gocache.NoExpiration)
if err != nil {
return "", false
}
return key[:index], true
}
func Redirect(key string, c *gocache.Cache) (bool, string, error) {
item, isExist := c.Get(key)
tmpUrl := ""
if isExist {
tmpUrl = item.(address).Url
item = address{tmpUrl, item.(address).Clicks + 1}
err := c.Replace(key, item, gocache.NoExpiration)
if err != nil {
return false, "", err
}
}
return isExist, tmpUrl, nil
}
func Print(c *gocache.Cache) string {
result := ""
for key, item := range c.Items() {
result += fmt.Sprintf("key:%v Url:%v Clicks:%d\n", key, item.Object.(address).Url, item.Object.(address).Clicks)
}
return result
}
func isExist(key string, c *gocache.Cache) bool {
_, isExist := c.Get(key)
return isExist
}
// isValidUrl tests a string to determine if it is a Url or not.
func isValidUrl(toTest string) bool {
_, err := url.ParseRequestURI(toTest)
if err != nil {
return false
} else {
re := regexp.MustCompile(`^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+`)
return re.MatchString(toTest)
}
}
func Save(path string, c *gocache.Cache, mux sync.Mutex) error {
mux.Lock()
defer mux.Unlock()
gob.Register(address{})
// create a file
dataFile, err := os.Create(path)
if err != nil {
return err
}
// serialize the data
dataEncoder := gob.NewEncoder(dataFile)
err = dataEncoder.Encode(c.Items())
if err != nil {
return err
}
dataFile.Close()
return nil
}
func Load(path string) (c *gocache.Cache, err error) {
var data map[string]gocache.Item
// open data file
gob.Register(address{})
dataFile, err := os.Open(path)
if err != nil {
return
}
dataDecoder := gob.NewDecoder(dataFile)
err = dataDecoder.Decode(&data)
if err != nil {
return
}
dataFile.Close()
return gocache.NewFrom(gocache.NoExpiration, gocache.NoExpiration, data), nil
}