/
server.go
275 lines (228 loc) · 6.4 KB
/
server.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package main
import (
"bytes"
"crypto/md5"
"encoding/hex"
"flag"
"github.com/nfnt/resize"
"image"
"image/color"
_ "image/gif"
"image/jpeg"
"image/png"
"io"
"io/ioutil"
"launchpad.net/goyaml"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
)
type proxyHandler struct {
Host string // host of proxy
Scheme string // scheme of the proxy (typically http)
Prefix string // path prefix for the proxy
Postfix string // path postfix for the proxy
Format string // image format on the proxy
Watermark string // filename of the watermark
Port string // Server port
Binding string // Server binding
watermarkImage image.Image
backgroundColor color.Color
}
func (h proxyHandler) urlFor(u *url.URL) *url.URL {
n := new(url.URL)
n.Scheme = h.Scheme
n.Host = h.Host
if len(strings.Split(u.Path, "/")) == 3 {
n.Path = h.Prefix + strings.Join(strings.Split(u.Path, "/")[2:], "")
} else {
log.Println(u.Path)
n.Path = h.Prefix + u.Path
}
n.Path = n.Path[0:strings.LastIndex(n.Path, ".")]
n.Path = n.Path + h.Postfix + "." + h.Format
n.RawQuery = ""
return n
}
func (h *proxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// TODO: Recover from panic and throw a 500
var (
status int
duration time.Duration
err1, err2, err3 error
resp *http.Response
m image.Image
)
startTime := time.Now()
resp, err1 = http.Get(h.urlFor(r.URL).String())
defer resp.Body.Close()
if err1 != nil || resp.StatusCode != http.StatusOK {
status = resp.StatusCode
w.WriteHeader(status)
}
if err1 == nil && resp.StatusCode == http.StatusOK {
m, _, err2 = image.Decode(resp.Body)
if err2 != nil {
status = http.StatusInternalServerError
w.WriteHeader(status)
} else {
status = http.StatusOK
err3 = h.serveImage(w, r, m)
if err3 != nil {
status = http.StatusInternalServerError
w.WriteHeader(status)
}
}
}
duration = time.Since(startTime)
logStatement := "%v\t%v\n"
logStatement += " Completed %d %v in %dms\n"
if err1 != nil {
logStatement += " error > " + err1.Error()
}
if err2 != nil {
logStatement += " error > " + err2.Error()
}
if err3 != nil {
logStatement += " error > " + err3.Error()
}
log.Printf(logStatement, r.Method, r.URL.String(), status, http.StatusText(status), int(duration.Nanoseconds()/1000000))
}
func (h *proxyHandler) resizeImage(m image.Image, options map[string]interface{}) image.Image {
dstRect := image.Rect(0, 0, options["width"].(int), options["height"].(int))
srcRect := m.Bounds()
srcRatio := float32(srcRect.Dx()) / float32(srcRect.Dy())
dstRatio := float32(dstRect.Dx()) / float32(dstRect.Dy())
var backgroundColor color.Color
if _, ok := options["backgroundColor"]; ok {
backgroundColor = options["backgroundColor"].(color.Color)
} else {
backgroundColor = h.backgroundColor
}
if options["crop"].(bool) {
m = resizeAndCrop(m, dstRect)
} else if options["enforce"].(bool) {
m = resize.Resize(uint(dstRect.Dx()), uint(dstRect.Dy()), m, resize.MitchellNetravali)
} else if options["minimum"].(bool) {
if srcRatio > dstRatio {
dstRect.Max.X = int(float32(dstRect.Max.Y) * srcRatio)
} else {
dstRect.Max.Y = int(float32(dstRect.Max.X) / srcRatio)
}
m = resize.Resize(uint(dstRect.Dx()), uint(dstRect.Dy()), m, resize.MitchellNetravali)
} else if options["maximum"].(bool) {
if srcRatio > dstRatio && srcRect.Dx() > dstRect.Dx() {
dstRect.Max.Y = int(float32(dstRect.Max.X) / srcRatio)
} else if srcRect.Dy() > dstRect.Dy() {
dstRect.Max.X = int(float32(dstRect.Max.Y) * srcRatio)
} else {
dstRect.Max.X = int(float32(srcRect.Max.Y) * srcRatio)
dstRect.Max.Y = int(float32(srcRect.Max.X) / srcRatio)
}
m = resize.Resize(uint(dstRect.Dx()), uint(dstRect.Dy()), m, resize.MitchellNetravali)
} else {
m = resizeAndPad(m, dstRect, backgroundColor)
}
return m
}
func (h *proxyHandler) serveImage(w http.ResponseWriter, r *http.Request, m image.Image) error {
options := extractOptions(r, m)
m = h.resizeImage(m, options)
var err error
m, err = h.watermark(m)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return err
}
const (
year = time.Hour * 24 * 7 * 52
timeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
)
w.Header().Set("Content-type", options["mimeType"].(string))
w.Header().Set("Expires", time.Now().Add(year).UTC().Format(timeFormat))
w.Header().Set("Cache-Control", "public, max-age=15724800")
etag := md5.New()
body := new(bytes.Buffer)
bodyWriter := io.MultiWriter(body, etag)
switch options["mimeType"].(string) {
case "image/jpeg":
err = jpeg.Encode(bodyWriter, m, &jpeg.Options{Quality: 85})
case "image/png":
err = png.Encode(bodyWriter, m)
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return err
} else {
w.Header().Set("ETag", hex.EncodeToString(etag.Sum(nil)))
body.WriteTo(w)
}
return nil
}
func parseConfigFile(n string) (*proxyHandler, error) {
file, err := os.Open(n)
if err != nil {
return nil, err
}
var h *proxyHandler
data, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
err = goyaml.Unmarshal(data, &h)
if err != nil {
return nil, err
}
if h.Watermark != "" {
file, err = os.Open(h.Watermark)
h.watermarkImage, _, err = image.Decode(file)
if err != nil {
return nil, err
}
}
h.backgroundColor = color.RGBA{80, 80, 80, 1}
return h, nil
}
var configFile string
var serverPort string
var serverBinding string
func init() {
flag.StringVar(&configFile, "config", "", "conf file (see config.yml.sample)")
flag.StringVar(&serverPort, "port", "3000", "run the server on the specified port")
flag.StringVar(&serverBinding, "binding", "0.0.0.0", "bind the server to the specified ip")
}
func main() {
flag.Parse()
var (
h *proxyHandler
err error
)
if configFile != "" {
h, err = parseConfigFile(configFile)
if err != nil {
log.Fatal("Unable to find / parse config file (does the watermark exists?).")
}
}
if h != nil {
if h.Port != "" && serverPort == "3000" {
serverPort = h.Port
}
if h.Binding != "" && serverBinding == "0.0.0.0" {
serverBinding = h.Binding
}
}
if h.Port != "" {
serverPort = h.Port
}
if h.Binding != "" {
serverBinding = h.Binding
}
http.Handle("/", h)
err = http.ListenAndServe(serverBinding+":"+serverPort, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}