-
Notifications
You must be signed in to change notification settings - Fork 0
/
cats.go
88 lines (69 loc) · 1.63 KB
/
cats.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
package main
import (
"errors"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"strings"
"github.com/unrolled/render"
)
type CatHandler struct {
pngs [][]byte
rend *render.Render
}
func NewCatHandler(imageDir string) (*CatHandler, error) {
c := &CatHandler{rend: render.New()}
files, err := ioutil.ReadDir(imageDir)
if err != nil {
return nil, err
}
for _, fileInfo := range files {
path := fmt.Sprintf("%s/%s", imageDir, fileInfo.Name())
if strings.HasSuffix(path, ".png") {
err := c.addPNG(path)
if err != nil {
return nil, err
}
}
}
return c, nil
}
func (c *CatHandler) Handler() http.Handler {
m := http.NewServeMux()
m.HandleFunc("/", c.serveIndex)
m.HandleFunc("/image.png", c.serveImage)
return m
}
func (c *CatHandler) addPNG(path string) error {
png, err := ioutil.ReadFile(path)
if err != nil {
return err
}
c.pngs = append(c.pngs, png)
return nil
}
func (c *CatHandler) randCat() ([]byte, error) {
if len(c.pngs) == 0 {
return nil, errors.New("no cat PNGs loaded")
}
return c.pngs[rand.Int()%len(c.pngs)], nil
}
func (c *CatHandler) serveIndex(w http.ResponseWriter, req *http.Request) {
page := map[string]interface{}{
"ImageID": rand.Int(),
}
c.rend.HTML(w, http.StatusOK, "index", page)
}
func (c *CatHandler) serveImage(w http.ResponseWriter, req *http.Request) {
png, err := c.randCat()
if err != nil {
Errorf(w, "Unable to retrieve random cat: %v", err)
return
}
w.Header().Set("Content-Type", "image/png")
w.Write(png)
}
func Errorf(w http.ResponseWriter, pat string, args ...interface{}) {
http.Error(w, fmt.Sprintf(pat, args...), http.StatusInternalServerError)
}