-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimggroupcache.go
68 lines (54 loc) · 1.45 KB
/
imggroupcache.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
package main
import (
"bytes"
"fmt"
"github.com/golang/groupcache"
"image"
_ "image/gif"
_ "image/jpeg"
"image/png"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
)
func renderImg(resp http.ResponseWriter, req *http.Request) {
req.ParseForm()
imgName := strings.Join(req.Form["img"], "")
imgName = fmt.Sprintf("imgs/%s", imgName)
if _, err := os.Stat(imgName); os.IsNotExist(err) {
http.NotFound(resp, req)
} else {
var buf []byte
err := cacher.Get(nil, imgName, groupcache.AllocatingByteSliceSink(&buf))
if err != nil {
fmt.Println("Get error when cacher.Get:", err)
}
img, format, err := image.Decode(bytes.NewBuffer(buf))
if err != nil {
fmt.Println("Get error when image.Decode:", err)
}
fmt.Println("format:", format)
png.Encode(resp, img)
}
}
func getImage(ctx groupcache.Context, key string, dest groupcache.Sink) error {
fmt.Println("Getting image from slow backend ... ")
time.Sleep(time.Duration(3000) * time.Millisecond)
imgData, err := ioutil.ReadFile(key)
if err != nil {
fmt.Println("Get error when ioutil.ReadFile:", err)
}
dest.SetBytes(imgData)
return nil
}
var cacher *groupcache.Group
func main() {
cacher = groupcache.NewGroup("cacher", 64<<20, groupcache.GetterFunc(getImage))
http.HandleFunc("/", renderImg)
err := http.ListenAndServe(":9000", nil)
if err != nil {
fmt.Println("Get error when http.ListenAndServe:", err)
}
}