-
Notifications
You must be signed in to change notification settings - Fork 4
/
loader.go
72 lines (56 loc) · 981 Bytes
/
loader.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
package web
import (
"bytes"
"io"
"net/http"
"net/url"
"github.com/gravestench/director/pkg/common/cache"
)
type Loader struct {
cache *cache.Cache
}
const (
imageBudget = 100
)
func New() *Loader {
return &Loader{
cache: cache.New(imageBudget),
}
}
func (l *Loader) Name() string {
return "HTTP Web Loader"
}
func (l *Loader) Exists(p string) bool {
if _, err := url.Parse(p); err != nil {
return false
}
resp, err := http.Get(p)
if err != nil {
return false
}
if resp.StatusCode != 200 {
return false
}
return true
}
func (l *Loader) Load(p string) (io.ReadSeeker, error) {
if entry, found := l.cache.Retrieve(p); found {
rs, ok := entry.(io.ReadSeeker)
if !ok {
return nil, nil
}
return rs, nil
}
resp, err := http.Get(p)
if err != nil {
return nil, err
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
go func() {
_ = l.cache.Insert(p, bytes.NewReader(data), 1)
}()
return nil, nil
}