/
shortener.go
78 lines (62 loc) · 1.29 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
package main
import (
"fmt"
"github.com/gosexy/redis"
"log"
)
var client *redis.Client
func init() {
client = redis.New()
err := client.Connect("localhost", 6379)
if err != nil {
log.Println(err)
fmt.Println("Failed to connect to the Redis Database")
}
}
func shorten(longUrl string) (string, error) {
if hasShortUrl(longUrl) {
return getShortUrl(longUrl), nil
}
code := generateRandomString(5)
_, err := client.HSet("longToShort", longUrl, code)
if err != nil {
return "", err
}
_, err = client.HSet("shortToLong", code, longUrl)
if err != nil {
return "", err
}
return code, nil
}
func getLongUrl(id string) string {
if !hasLongUrl(id) {
return "URL Not Found!"
}
return hget("shortToLong", id)
}
func hasShortUrl(longUrl string) bool {
return hexist("longToShort", longUrl)
}
func hasLongUrl(id string) bool {
return hexist("shortToLong", id)
}
func getShortUrl(longUrl string) string {
if !hasShortUrl(longUrl) {
return "URL Not Found!"
}
return hget("longToShort", longUrl)
}
func hexist(key, field string) bool {
exists, err := client.HExists(key, field)
if err != nil {
return false
}
return exists
}
func hget(key, field string) string {
result, err := client.HGet(key, field)
if err != nil {
return "An error has occurred!"
}
return result
}