-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
62 lines (51 loc) · 1.02 KB
/
db.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
package webfinger
import (
"encoding/json"
"errors"
)
// ErrResNotFound is thrown when resource is not in DB
var ErrResNotFound = errors.New("resource not found")
// DB storage interface
type DB interface {
// Get the resource from DB
Get(q *Query) (*Resource, error)
}
// MemDB memory implementation of DB interface
type MemDB struct {
m map[string][]byte
}
// NewMemDB returns a new memory DB
func NewMemDB(m map[string][]byte) *MemDB {
return &MemDB{
m: m,
}
}
// Get the resource from DB
func (db *MemDB) Get(q *Query) (*Resource, error) {
data, ok := db.m[q.Resource]
if !ok {
return nil, ErrResNotFound
}
// decode resource
res := &Resource{}
err := json.Unmarshal(data, res)
if err != nil {
return nil, err
}
// filter links
links := res.Links
if q.Rel != nil {
links = []*Link{}
idx := map[string]*Link{}
for _, l := range res.Links {
idx[l.Rel] = l
}
for _, rel := range q.Rel {
if l, ok := idx[rel]; ok {
links = append(links, l)
}
}
}
res.Links = links
return res, nil
}