-
Notifications
You must be signed in to change notification settings - Fork 1
/
shorturl.go
49 lines (42 loc) · 994 Bytes
/
shorturl.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
// Copyright 2015 Luke Shumaker
// Copyright 2015 Davis Webb
package backend
import (
"locale"
"net/url"
"periwinkle"
)
type ShortURL struct {
ID string
Dest string //*url.URL // TODO: figure out how to have (un)marshalling happen automatically
}
func (o ShortURL) dbSchema(db *periwinkle.Tx) locale.Error {
return locale.UntranslatedError(db.CreateTable(&o).
AddUniqueIndex("dest_idx", "dest").
Error)
}
func NewShortURL(db *periwinkle.Tx, u *url.URL) *ShortURL {
o := ShortURL{
ID: RandomString(5),
Dest: u.String(), // TODO: automatic marshalling
}
if err := db.Create(&o).Error; err != nil {
dbError(err)
}
return &o
}
func (o *ShortURL) Save(db *periwinkle.Tx) {
if err := db.Save(o).Error; err != nil {
dbError(err)
}
}
func GetShortURLByID(db *periwinkle.Tx, id string) *ShortURL {
var o ShortURL
if result := db.First(&o, "id = ?", id); result.Error != nil {
if result.RecordNotFound() {
return nil
}
dbError(result.Error)
}
return &o
}