/
web.go
225 lines (180 loc) · 5.56 KB
/
web.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
package main
import (
"database/sql"
"fmt"
"github.com/bmizerany/pat"
"github.com/gorilla/context"
"html/template"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
)
const (
// Maximum number of bytes to be stored in memory when parsing multipart
// forms. The rest will be stored in temp files.
MaxMultipartMemory = 100000
)
var (
templates map[string]*template.Template
)
const (
SearchImageByTitleSql = "SELECT title, orig_filename, height, width, hash FROM images WHERE LOWER(title) LIKE $1"
RecentImageSql = "SELECT title, orig_filename, height, width, hash, created_at FROM images ORDER BY created_at LIMIT 5"
)
func registerRoutes() http.Handler {
h := http.NewServeMux()
mux := pat.New()
// register routes
mux.Get("/", http.HandlerFunc(root))
mux.Get("/upload", oauthWrapper(http.HandlerFunc(uploadPage)))
mux.Post("/upload", oauthWrapper(http.HandlerFunc(uploadHandler)))
mux.Get("/auth", http.HandlerFunc(oauthRedirectHandler))
mux.Get("/search", http.HandlerFunc(searchPage))
mux.Get("/image/:hash", http.HandlerFunc(imagePage))
mux.Get("/:hash", http.HandlerFunc(getImageHandler))
mux.Get("/:hash/:width", http.HandlerFunc(getImageHandlerWidth))
mux.Get("/", http.HandlerFunc(root))
h.Handle("/", loggerMiddlerware(mux))
h.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
// load templates
templates = loadTemplates()
return context.ClearHandler(h)
}
func root(w http.ResponseWriter, r *http.Request) {
data := make(map[string]imageRecord)
rows, err := recentImageStmt.Query()
if err != nil {
log.Printf("Error when executing the query: %v", err)
fmt.Fprintf(w, "Sorry something went wrong...")
return
}
for rows.Next() {
var image imageRecord
if err := rows.Scan(&image.Title, &image.OriginalFilename, &image.Height, &image.Width, &image.Hash, &image.Created); err != nil {
log.Printf("Error: %v", err)
} else {
log.Printf("matched query: " + image.Hash + " " + image.Title)
data[image.Hash] = image
}
}
renderTemplate(w, "index", data)
}
func uploadPage(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "upload", nil)
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
file, header, err := r.FormFile("image")
if err != nil {
renderTemplate(w, "upload", map[string]string{"FormError": "Could not upload file."})
return
}
defer file.Close()
imgHash, err := saveFile(r.FormValue("title"), file, header)
if err != nil {
log.Printf("Error while saving image: %v", err)
renderTemplate(w, "upload", map[string]string{
"FormError": "Could not upload file: " + err.Error(),
})
} else {
http.Redirect(w, r, fmt.Sprintf("/image/%s", imgHash), http.StatusFound)
}
}
func getImageHandler(w http.ResponseWriter, r *http.Request) {
r.URL.Query().Add(":width", "0")
getImageHandlerWidth(w, r)
}
func getImageHandlerWidth(w http.ResponseWriter, r *http.Request) {
hash := r.URL.Query().Get(":hash")
width, err := strconv.Atoi(r.URL.Query().Get(":width"))
if err != nil {
width = 0
}
path, err := getImagePath(hash, width)
switch {
case err == nil:
http.ServeFile(w, r, path)
case err == sql.ErrNoRows:
http.NotFound(w, r)
default:
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func searchPage(w http.ResponseWriter, r *http.Request) {
value := r.URL.Query().Get("q")
searchterm := "%" + value + "%"
data := make(map[string]imageRecord)
if value == "" {
renderTemplate(w, "search", data)
return
}
rows, err := searchImageByTitleStmt.Query(searchterm)
if err != nil {
log.Printf("Error when executing the query: %v", err)
fmt.Fprintf(w, "Sorry something went wrong...")
return
}
for rows.Next() {
var image imageRecord
if err := rows.Scan(&image.Title, &image.OriginalFilename, &image.Height, &image.Width, &image.Hash); err != nil {
log.Printf("Error: %v", err)
} else {
log.Printf("matched query: " + image.Hash + " " + image.Title)
data[image.Hash] = image
}
}
renderTemplate(w, "search", data)
}
func imagePage(w http.ResponseWriter, r *http.Request) {
img, err := getImageByHash(r.URL.Query().Get(":hash"))
if err != nil {
// TODO: render proper 404 error page for missing images
http.Error(w, err.Error(), http.StatusNotFound)
return
}
renderTemplate(w, "image", img)
}
func loggerMiddlerware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Incoming request: [%s] %s", r.Method, r.URL.String())
h.ServeHTTP(w, r)
})
}
func renderTemplate(w http.ResponseWriter, name string, data interface{}) {
var tmpl *template.Template
if env.dev() {
var err error
tmpl, err = template.New("t").ParseFiles("template/layout.html", "template/"+makeFullTemplateName(name))
if err != nil {
http.Error(w, fmt.Sprintf("Error in template:\n%s", err), http.StatusInternalServerError)
return
}
} else {
tmpl = templates[makeFullTemplateName(name)]
}
if err := tmpl.ExecuteTemplate(w, "layout", data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func makeFullTemplateName(name string) string {
if !strings.HasSuffix(name, ".html") {
return name + ".html"
}
return name
}
func loadTemplates() map[string]*template.Template {
const layoutTemplate = "template/layout.html"
files, err := ioutil.ReadDir("template")
if err != nil {
log.Fatal(err)
}
result := make(map[string]*template.Template)
for _, file := range files {
if file.Name() != "layout.html" {
result[file.Name()] = template.Must(
template.ParseFiles(layoutTemplate, "template/"+file.Name()))
}
}
return result
}