-
Notifications
You must be signed in to change notification settings - Fork 2
/
fragment.go
111 lines (89 loc) · 2.25 KB
/
fragment.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package canoe
import (
"fmt"
"io/ioutil"
"net/http"
"sync"
"github.com/chrismckenzie/canoe/html"
)
// FragmentResolver is used to retrieve fragment.
type FragmentResolver interface {
ResolveByID(id string) ([]byte, error)
}
// FragmentHandler ...
type FragmentHandler struct {
fr FragmentResolver
}
// FragmentHandlerOption ...
type FragmentHandlerOption func(*FragmentHandler)
// NewFragmentHandler ...
func NewFragmentHandler(opts ...FragmentHandlerOption) *FragmentHandler {
var fh FragmentHandler
for _, opt := range opts {
opt(&fh)
}
return &fh
}
func (fh *FragmentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
id := r.URL.Path[len("/fragments/"):]
if len(id) <= 0 {
http.Error(w, "id in path is required", http.StatusBadRequest)
return
}
fragment, err := fh.fr.ResolveByID(id)
if err != nil {
http.Error(w, "unable to retrieve fragment", http.StatusNotFound)
}
w.Write(fragment)
}
// WithHTTPResolver ...
func WithHTTPResolver(fr *HTTPFragmentResolver) func(fh *FragmentHandler) {
return func(fh *FragmentHandler) {
fh.fr = fr
}
}
// HTTPFragmentResolver ...
type HTTPFragmentResolver struct {
client *http.Client
cache FragmentCache
}
// NewHTTPFragmentResolver ...
func NewHTTPFragmentResolver(c *http.Client, fc FragmentCache) *HTTPFragmentResolver {
return &HTTPFragmentResolver{c, fc}
}
// ResolveByID ...
func (fr HTTPFragmentResolver) ResolveByID(id string) ([]byte, error) {
if fragment, ok := fr.cache.Get(id); ok {
res, err := fr.client.Get(fragment.Href)
if err != nil {
return nil, err
}
if res.StatusCode >= http.StatusBadRequest {
return nil, fmt.Errorf("unable to resolve fragment: got %d", res.StatusCode)
}
byt, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return byt, nil
}
return nil, fmt.Errorf("no fragment exist by given id: %s", id)
}
type MemoryCache struct {
store map[string]html.Fragment
mu sync.Mutex
}
func NewMemoryCache() *MemoryCache {
return &MemoryCache{make(map[string]html.Fragment), sync.Mutex{}}
}
func (c *MemoryCache) Add(f html.Fragment) {
c.mu.Lock()
defer c.mu.Unlock()
c.store[f.ID] = f
}
func (c *MemoryCache) Get(id string) (html.Fragment, bool) {
c.mu.Lock()
defer c.mu.Unlock()
f, ok := c.store[id]
return f, ok
}