/
imageStore.go
75 lines (61 loc) · 1.35 KB
/
imageStore.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
package storage
import (
"crypto/sha1"
"fmt"
"net/http"
"strings"
"time"
"io/ioutil"
bolt "go.etcd.io/bbolt"
"github.com/timshannon/bolthold"
)
type ImageStore interface {
Get(hash string) []byte
Insert(uri string) (string, error)
}
type defaultImageStore struct {
store *bolthold.Store
}
func newDefaultImageStore(store *bolthold.Store) (defaultImageStore, error) {
db := store.Bolt()
err := db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("ImageStore"))
if err != nil {
return err
}
return nil
})
return defaultImageStore{store}, err
}
func (dis defaultImageStore) Get(hash string) []byte {
var data []byte
db := dis.store.Bolt()
db.View(func(tx *bolt.Tx) error {
data = tx.Bucket([]byte("ImageStore")).Get([]byte(hash))
return nil
})
return data
}
func (dis defaultImageStore) Insert(uri string) (string, error) {
if !strings.HasPrefix(uri, "http") {
return "", nil
}
client := http.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Get(uri)
if err != nil {
return "", err
}
defer resp.Body.Close()
image, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
hash := fmt.Sprintf("%x", sha1.Sum(image))
db := dis.store.Bolt()
err = db.Update(func(tx *bolt.Tx) error {
return tx.Bucket([]byte("ImageStore")).Put([]byte(hash), image)
})
return hash, err
}