-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
75 lines (63 loc) · 1.67 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
package main
import (
"html/template"
"log"
"net/http"
)
var (
userID = 0
)
type PhotoListHandler struct {
St *StDb
Tmpl *template.Template
}
func (h *PhotoListHandler) List(w http.ResponseWriter, r *http.Request) {
items, err := h.St.GetPhotos(userID)
if err != nil {
log.Println("failed to get Items", err)
http.Error(w, "storage error", http.StatusInternalServerError)
return
}
err = h.Tmpl.Execute(w, struct {
Items []*Photo
}{
Items: items,
})
if err != nil {
log.Println("failed to execute template", err)
http.Error(w, "failed to execute template", http.StatusInternalServerError)
return
}
}
func (h PhotoListHandler) Upload(w http.ResponseWriter, r *http.Request) {
uploadData, _, err := r.FormFile("my_file")
if err != nil {
log.Printf("failed to parse uploaded form file: %v", err)
http.Error(w, "parse form file 'my_file' error", http.StatusInternalServerError)
return
}
defer uploadData.Close()
md5Sum, err := SaveFile(uploadData)
if err != nil {
log.Printf("failed to save uploaded form file: %v", err)
http.Error(w, "save file error", http.StatusInternalServerError)
return
}
realFile := "./images/" + md5Sum + ".jpg"
err = MakeThumbnail(realFile, md5Sum)
if err != nil {
log.Printf("failed to create thumbnail for uploaded form file: %v", err)
http.Error(w, "thumbnail file creating error", http.StatusInternalServerError)
return
}
err = h.St.Add(&Photo{
Path: md5Sum,
UserID: userID,
})
if err != nil {
log.Printf("failed to store file info into storage: %v", err)
http.Error(w, "failed to store file info into storage", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}