-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
91 lines (77 loc) · 2.14 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"net/http"
"strings"
"text/template"
"github.com/disintegration/imaging"
"github.com/ggicci/httpin"
)
func index(w http.ResponseWriter, r *http.Request) {
it, _ := template.ParseFiles("index.html")
err := it.Execute(w, nil)
if err != nil {
http.Error(w, "Internal Error", http.StatusBadRequest)
return
}
}
type ResultHandlerForm struct {
Images []httpin.File `in:"form=images"`
ScaleFactor int `in:"form=scale-factor"`
OutputImageFormat string `in:"form=output-image-format"`
}
func result(w http.ResponseWriter, r *http.Request) {
form := r.Context().Value(httpin.Input).(*ResultHandlerForm)
encoder := imageEncoders[ImageEncoding(form.OutputImageFormat)]
if encoder == nil {
http.Error(w, "Internal Error", http.StatusBadRequest)
return
}
for _, i := range form.Images {
if !i.Valid {
http.Error(w, "Internal Error", http.StatusBadRequest)
return
}
}
// possible memory attack vector
if form.ScaleFactor < 1 || form.ScaleFactor > 20 {
http.Error(w, "Internal Error", http.StatusBadRequest)
return
}
resultModel := struct {
Mime string
Images []struct {
Upscaled string
Original string
}
}{
Mime: strings.ToLower(form.OutputImageFormat),
}
for _, i := range form.Images {
original, config, err := parseImageAndImageConfig(i)
if err != nil {
http.Error(w, "Internal Error", http.StatusBadRequest)
return
}
upscaled := imaging.Resize(original, config.Width*form.ScaleFactor, config.Height*form.ScaleFactor, imaging.NearestNeighbor)
upscaledBase64, err := encoder.encodeImage(upscaled)
if err != nil {
http.Error(w, "Internal Error", http.StatusBadRequest)
return
}
originalBase64, err := encoder.encodeImage(original)
if err != nil {
http.Error(w, "Internal Error", http.StatusBadRequest)
return
}
resultModel.Images = append(resultModel.Images, struct {
Upscaled string
Original string
}{Upscaled: upscaledBase64, Original: originalBase64})
}
rt, _ := template.ParseFiles("result.html")
err := rt.Execute(w, resultModel)
if err != nil {
http.Error(w, "Internal Error", http.StatusBadRequest)
return
}
}