-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
64 lines (56 loc) · 1.26 KB
/
service.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
package main
import (
"database/sql"
"errors"
"github.com/bradfitz/gomemcache/memcache"
)
type LinkService interface {
Get(slug string) (string, error)
Create(url string) (Link, error)
}
type linkService struct {
cache *memcache.Client
db *sql.DB
}
var ErrDecodeFailure = errors.New("cannot decode slug")
var ErrNotFound = errors.New("link not found")
func (service linkService) Get(slug string) (string, error) {
item, err := service.cache.Get(slug)
if err == nil {
// Cache hit
return string(item.Value), nil
}
// Cache miss or malformed key
id, err := Decode(slug)
if err != nil {
return "", ErrDecodeFailure
}
var url string
query := `
SELECT url FROM links
WHERE id=$1
`
err = service.db.QueryRow(query, id).Scan(&url)
if err != nil {
// No rows returned or serial overflow
return "", ErrNotFound
}
// Write to cache, but serve request even on error
item = &memcache.Item{Key: slug, Value: []byte(url)}
service.cache.Set(item)
return url, nil
}
func (service linkService) Create(url string) (Link, error) {
query := `
INSERT INTO links(url)
VALUES ($1)
RETURNING id
`
id := 0
err := service.db.QueryRow(query, url).Scan(&id)
if err != nil {
return Link{}, err
}
slug, err := Encode(id)
return Link{url, &slug}, err
}