forked from cdnbacon/coresize
/
handlers.go
69 lines (60 loc) · 1.97 KB
/
handlers.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
package coresize
import (
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/julienschmidt/httprouter"
"github.com/kiasaki/batbelt/rest"
)
func (s *Server) handlePanic(w http.ResponseWriter, r *http.Request, err interface{}) {
rest.SetInternalServerErrorResponse(w, err)
}
func (s *Server) handleNotFound(w http.ResponseWriter, r *http.Request) {
rest.SetNotFoundResponse(w)
}
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// return supported endpoints with url templates
rest.SetOKResponse(w, map[string]interface{}{
"v1": map[string]string{
"root_url": "/",
"image_url": "/v1/i/{/file_name}{?file_hash,height,width,allign}",
},
})
}
func (s *Server) handleImage(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestFilename := ps.ByName("filename")[1:]
if cacheFile, ok := s.Cache.Get(requestFilename); ok {
// extract url params
height, _ := strconv.Atoi(r.URL.Query().Get("height"))
width, _ := strconv.Atoi(r.URL.Query().Get("width"))
align := r.URL.Query().Get("align")
if align == "" {
align = "cc"
}
// fetch and render, or, read from disk
image, err := cacheFile.Image()
w.Header().Set("Content-Type", cacheFile.FileType())
w.Header().Set("Expires", time.Now().AddDate(1, 0, 0).Format(http.TimeFormat))
w.Header().Set("ETag", fmt.Sprintf("%s,w=%d,h=%d,a=%s", image.Hash, width, height, align))
err = image.Render(w, width, height, align)
if err != nil {
log.Printf("Error rendering %s: %s\n", requestFilename, err.Error())
rest.SetInternalServerErrorResponse(w, err)
return
}
return
}
http.Error(w, "File not found", http.StatusNotFound)
}
func (s *Server) handleReload(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
cache := NewCache(s.Config)
if err := cache.Setup(); err != nil {
log.Printf("Error setting up cache: %s\n", err.Error())
rest.SetInternalServerErrorResponse(w, err)
return
}
s.Cache = cache
rest.SetNoContentResponse(w)
}