-
Notifications
You must be signed in to change notification settings - Fork 16
/
urls.go
96 lines (77 loc) · 1.35 KB
/
urls.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
package main
import (
"log"
"github.com/boltdb/bolt"
)
// URL ...
type URL struct {
id string
url string
}
// ID ...
func (u URL) ID() string {
return u.id
}
// URL ...
func (u URL) URL() string {
return u.url
}
// Save ...
func (u URL) Save() error {
log.Printf("u: %v", u)
if u.id == "" || u.url == "" {
log.Printf("u is nil :/")
return nil
}
err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte("urls"))
if err != nil {
log.Printf("create bucket failed: %s", err)
return err
}
err = b.Put([]byte(u.id), []byte(u.url))
if err != nil {
log.Printf("put key failed: %s", err)
return err
}
return nil
})
return err
}
// LookupURL ...
func LookupURL(id string) (u URL, ok bool) {
err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("urls"))
if b == nil {
return nil
}
v := b.Get([]byte(id))
if v != nil {
u = URL{id: id, url: string(v)}
ok = true
}
return nil
})
if err != nil {
log.Printf("error looking up url for %s: %s", id, err)
}
return
}
// NewURL ...
func NewURL(url string) (u URL, err error) {
log.Printf("NewURL: %v", url)
var id string
for {
// TODO: Make length (5) configurable
id = RandomString(5)
_, ok := LookupURL(id)
if ok {
continue
} else {
break
}
}
u = URL{id: id, url: url}
err = u.Save()
return
}