/
app.go
95 lines (81 loc) · 2.33 KB
/
app.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
package main
import (
"bytes"
"encoding/base64"
"image"
"image/jpeg"
"io"
"log"
"net/http"
"os"
"text/template"
)
var templates = template.Must(template.ParseFiles("templates/index.html", "templates/show.html"))
func IndexHandler(w http.ResponseWriter, r *http.Request) {
data := map[string]interface{}{"Title": "index"}
renderTemplate(w, "index", data)
}
func UploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Allowed POST method only", http.StatusMethodNotAllowed)
return
}
err := r.ParseMultipartForm(32 << 20) // maxMemory
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
file, _, err := r.FormFile("upload")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()
f, err := os.Create("/tmp/test.jpg")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
io.Copy(f, file)
http.Redirect(w, r, "/show", http.StatusFound)
}
func ShowHandler(w http.ResponseWriter, r *http.Request) {
file, err := os.Open("/tmp/test.jpg")
defer file.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
img, _, err := image.Decode(file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeImageWithTemplate(w, "show", &img)
}
func renderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
if err := templates.ExecuteTemplate(w, tmpl+".html", data); err != nil {
log.Fatalln("Unable to execute template.")
}
}
func writeImageWithTemplate(w http.ResponseWriter, tmpl string, img *image.Image) {
buffer := new(bytes.Buffer)
if err := jpeg.Encode(buffer, *img, nil); err != nil {
log.Fatalln("Unable to encode image.")
}
// w.Header().Set("Content-Type", "image/jpeg")
// w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
// if _, err := w.Write(buffer.Bytes()); err != nil {
// log.Println("unable to write image.")
// }
str := base64.StdEncoding.EncodeToString(buffer.Bytes())
data := map[string]interface{}{"Title": tmpl, "Image": str}
renderTemplate(w, tmpl, data)
}
func main() {
http.HandleFunc("/", IndexHandler)
http.HandleFunc("/upload", UploadHandler)
http.HandleFunc("/show", ShowHandler)
http.ListenAndServe(":8888", nil)
}