/
controllers.go
186 lines (145 loc) · 4.28 KB
/
controllers.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package main
import (
"bytes"
"fmt"
"github.com/bradberger/optimizer"
"github.com/gorilla/mux"
"github.com/mailgun/log"
_ "golang.org/x/image/bmp"
_ "golang.org/x/image/tiff"
_ "golang.org/x/image/webp"
_ "golang.org/x/image/webp/nycbcra"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io/ioutil"
"mime"
"net/http"
"path"
)
func cdnHeaders(w *http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
(*w).Header().Set("Access-Control-Allow-Origin", origin)
(*w).Header().Set("Timing-Allow-Origin", origin)
(*w).Header().Set("Access-Control-Allow-Methods", r.Method)
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding")
}
}
func imgHeaders(w *http.ResponseWriter, r *http.Request) {
cdnHeaders(w, r)
(*w).Header().Set("Accept-CH", "DPR, Width, Viewport-Width, Downlink")
(*w).Header().Set("Vary", "Accept, DPR, Width, Save-Data, Downlink")
}
func serveCachedRespImg(w http.ResponseWriter, r *http.Request, domain string, imagePath string, opts optimizer.Options) (err error) {
cachePath := getOptimizedImgCachePath(domain, imagePath, opts)
contents, err := ioutil.ReadFile(path.Clean(cachePath))
if err == nil {
// Set Content-Type and Cache-Control headers.
w.Header().Set("Content-Type", opts.Mime)
imgHeaders(&w, r)
addCacheHeader(&w, "optimized")
w.Write(contents)
return
}
return
}
func getFileFromUpstream(fileURL string, useSSL bool) (body []byte, statusCode int, err error) {
// Try to fetch the image. If not, fail.
url := fileURL
if useSSL {
url = fmt.Sprintf("https://%s", url)
} else {
url = fmt.Sprintf("http://%s", url)
}
resp, e := http.Get(url)
if e != nil {
err = e
log.Errorf("Couldn't get %s", url)
statusCode = 500
return
}
defer resp.Body.Close()
// Make sure the request succeeded
if resp.StatusCode > 302 {
log.Errorf("Couldn't fetch %s", url)
statusCode = resp.StatusCode
return
}
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("Couldn't read body %s", url)
statusCode = 500
}
return
}
func getImageFromUpstream(domain string, imagePath string) (body []byte, statusCode int, err error) {
// Check for resized original on disk.
body, err = getImageFromCache(fmt.Sprintf("%s/%s/%s", tmpDir, domain, imagePath))
if err != nil {
body, statusCode, err = getFileFromUpstream(fmt.Sprintf("%s/%s", domain, imagePath), false)
}
return
}
func respLocalImgHandler(w http.ResponseWriter, r *http.Request) {
domain := r.Host
imagePath := r.RequestURI
opts := optimizer.Options{
Mime: mime.TypeByExtension(path.Ext(imagePath)),
}
opts.SetFromRequest(r)
opts.Optimize()
// Try to fetch cached iamge.
if err := serveCachedRespImg(w, r, domain, imagePath, opts); err == nil {
imgHeaders(&w, r)
return
}
body, err := getImageFromCache(fmt.Sprintf("%s/%s", documentRoot, imagePath))
if err != nil {
http.Error(w, http.StatusText(404), 404)
return
}
optimizeAndServeImg(w, r, opts, domain, imagePath, body)
}
func optimizeAndServeImg(w http.ResponseWriter, r *http.Request, opts optimizer.Options, domain string, imagePath string, body []byte) (err error) {
img, _, err := image.Decode(bytes.NewReader(body))
if err != nil || img == nil {
log.Errorf("Could not decode %s/%s: %s", domain, imagePath, err.Error())
return
}
// If decoding succeeds, cache it.
go cacheDomainFile(domain, imagePath, body)
// If cache enabled, cache the file.
imgHeaders(&w, r)
if useFileCache {
writeAndCacheImg(w, img, opts, getOptimizedImgCachePath(domain, imagePath, opts))
return
}
// If cache disabled, just serve
optimizer.Encode(w, img, opts)
return
}
func respRemoteImgHandler(w http.ResponseWriter, r *http.Request) {
var body []byte
vars := mux.Vars(r)
imagePath := vars["path"]
domain := vars["domain"]
// Set up options
opts := optimizer.Options{
Mime: mime.TypeByExtension(path.Ext(imagePath)),
}
opts.SetFromRequest(r)
opts.Optimize()
// Try to fetch cached iamge.
if err := serveCachedRespImg(w, r, domain, imagePath, opts); err == nil {
return
}
body, statusCode, err := getImageFromUpstream(domain, imagePath)
if err != nil {
imgHeaders(&w, r)
http.Error(w, http.StatusText(statusCode), statusCode)
return
}
optimizeAndServeImg(w, r, opts, domain, imagePath, body)
return
}