-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
280 lines (238 loc) · 6.13 KB
/
main.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
276
277
278
279
280
package main
import (
"crypto/sha1"
"fmt"
"image"
"image/jpeg"
"io"
"log"
"os"
"path"
"path/filepath"
"strconv"
"time"
"github.com/spf13/viper"
"github.com/disintegration/imaging"
// https://golang.org/pkg/net/http/
"net/http"
)
// https://yourbasic.org/golang/iota/
// https://github.com/nfnt/resize
func resizeImage() {
}
// MustInt converts a string to int. On error the
// default value will be returned.
func MustInt(input string, default_ int) int {
if value, err := strconv.Atoi(input); err != nil {
return default_
} else {
return value
}
}
type ImageMethod int
const (
MethodResize ImageMethod = iota
MethodFill
MethodFit
endMethod
)
func validateImageMethod(value int) error {
if value < int(endMethod) {
return nil
}
return NewBadRequest("Invalid Method")
}
type Options struct {
CacheDir string
ImageDir string
DefaultMethod ImageMethod
}
func GetOptions() Options {
return Options{
CacheDir: viper.GetString("cache_dir"),
ImageDir: viper.GetString("image_dir"),
DefaultMethod: MethodFill,
}
}
func hashIt(filename string, method, height, width, anchor, interpolation int) string {
h := sha1.New()
io.WriteString(h, strconv.FormatInt(int64(height), 10))
io.WriteString(h, strconv.FormatInt(int64(width), 10))
io.WriteString(h, filename)
io.WriteString(h, strconv.FormatInt(int64(interpolation), 10))
io.WriteString(h, strconv.FormatInt(int64(method), 10))
io.WriteString(h, strconv.FormatInt(int64(anchor), 10))
return fmt.Sprintf("%x", string(h.Sum(nil)))
}
func MustCacheDir(cacheDir string) {
if err := os.MkdirAll(cacheDir, os.ModeDir); err != nil {
if os.IsExist(err) {
log.Println("Cache dir already exists")
} else {
log.Fatal(err)
}
}
}
type ResampleFilter int
const (
NearestNeighbor ResampleFilter = iota
Box
Linear
Hermite
MitchellNetravali
CatmullRom
BSpline
Gaussian
Bartlett
Lanczos
Hann
Hamming
Blackman
Welch
Cosine
endRF
)
func GetResampleFilter(input ResampleFilter) (imaging.ResampleFilter, error) {
if int(endRF) < int(input) {
return imaging.ResampleFilter{}, NewBadRequest(fmt.Sprintf("Invalid resample filter: %d", input))
}
switch input {
case NearestNeighbor:
return imaging.NearestNeighbor, nil
case Box:
return imaging.Box, nil
case Linear:
return imaging.Linear, nil
case Hermite:
return imaging.Hermite, nil
case MitchellNetravali:
return imaging.MitchellNetravali, nil
case CatmullRom:
return imaging.CatmullRom, nil
case BSpline:
return imaging.BSpline, nil
case Gaussian:
return imaging.Gaussian, nil
case Bartlett:
return imaging.Bartlett, nil
case Lanczos:
return imaging.Lanczos, nil
case Hann:
return imaging.Hann, nil
case Hamming:
return imaging.Hamming, nil
case Blackman:
return imaging.Blackman, nil
case Welch:
return imaging.Welch, nil
case Cosine:
return imaging.Cosine, nil
default:
return imaging.NearestNeighbor, nil
}
}
func applyImage(
filename string, method ImageMethod,
height, width int, interp ResampleFilter, anchor imaging.Anchor,
opts Options) (image.Image, error) {
// TODO: create safe path
imagePath := path.Join(opts.ImageDir, filename)
if _, err := os.Stat(imagePath); os.IsNotExist(err) {
return nil, FileNotFound{filename}
}
ext := filepath.Ext(filename)
cacheHash := hashIt(filename, int(method), height, width, int(anchor), int(interp))
cacheName := fmt.Sprintf("%s%s", cacheHash, ext)
MustCacheDir(opts.CacheDir)
cacheFullPath := path.Join(opts.CacheDir, cacheName)
if _, err := os.Stat(cacheFullPath); os.IsNotExist(err) {
file, _ := os.Open(imagePath)
img, _ := jpeg.Decode(file)
file.Close()
var m image.Image
filter, err := GetResampleFilter(interp)
if err != nil {
return nil, err
}
switch method {
case MethodResize:
m = imaging.Resize(img, width, height, filter)
case MethodFit:
m = imaging.Fit(img, width, height, filter)
case MethodFill:
m = imaging.Fill(img, width, height, imaging.Anchor(anchor), filter)
default:
m = imaging.Resize(img, width, height, filter)
}
if out, oerr := os.Create(cacheFullPath); oerr != nil {
log.Fatal(oerr)
} else {
defer out.Close()
jpeg.Encode(out, m, nil)
return m, nil
}
} else {
file, _ := os.Open(cacheFullPath)
img, _ := jpeg.Decode(file)
defer file.Close()
return img, nil
}
return nil, nil
}
func imageHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Query().Get("f")
anchor := MustInt(r.URL.Query().Get("a"), 0)
height := MustInt(r.URL.Query().Get("h"), 0)
width := MustInt(r.URL.Query().Get("w"), 0)
interpolation := MustInt(r.URL.Query().Get("i"), 0)
method := MustInt(r.URL.Query().Get("m"), 0)
if img, err := applyImage(filename, ImageMethod(method), height, width, ResampleFilter(interpolation), imaging.Anchor(anchor), GetOptions()); err != nil {
if _, ok := err.(BadRequest); ok {
w.WriteHeader(http.StatusBadRequest)
}
if _, ok := err.(FileNotFound); ok {
w.WriteHeader(http.StatusNotFound)
}
io.WriteString(w, err.Error())
} else {
jpeg.Encode(w, img, nil)
}
}
type FileNotFound struct {
Filename string
}
func (f FileNotFound) Error() string {
return fmt.Sprintf("File not found: %s", f.Filename)
}
type BadRequest struct {
Message string
}
func (b BadRequest) Error() string {
return b.Message
}
func NewBadRequest(message string) BadRequest {
return BadRequest{message}
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s -- [%s] -- %s %s -- %d",
time.Now().UTC().Format("2006-01-02T15:04:05.999Z"),
r.Method, r.URL.Path, r.URL.Query().Encode(), r.ContentLength)
imageHandler(w, r)
})
// TODO: /list
viper.SetDefault("cache_dir", "_cache")
viper.SetDefault("image_dir", "input")
viper.SetDefault("bind", "127.0.0.1:8080")
viper.SetDefault("default_method", MethodResize)
viper.SetDefault("default_filter", NearestNeighbor)
viper.SetDefault("default_anchor", imaging.Center)
viper.SetConfigName("config")
err := viper.ReadInConfig()
if err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
}
log.Fatal(http.ListenAndServe(viper.GetString("bind"), nil))
}