-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
295 lines (257 loc) · 6.81 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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
)
func imageHandler(w http.ResponseWriter, r *http.Request) {
log.Println("received request for", r.URL.Path)
ex := mime.TypeByExtension(r.URL.Path[strings.LastIndex(r.URL.Path, "."):])
w.Header()["Content-Type"] = []string{ex}
content, err := pages.ReadFile("static/" + r.URL.Path[1:])
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
w.Header().Set("Cache-Control", "public, max-age=604800")
w.Write(content)
}
func apiHandler(w http.ResponseWriter, req *http.Request) {
log.Println("received api request")
lang, ok := req.URL.Query()["lang"]
if !ok {
lang = []string{"pt"}
}
pg := req.URL.Query()["page"]
if len(pg) == 0 {
pg = []string{"0"}
}
page, _ := strconv.Atoi(pg[0])
name := req.URL.Query()["name"]
ingredients := req.URL.Query()["ingredients"]
// The query part
var results []recipe
var err error
if len(name) > 0 {
log.Println("getting recipes by name for", lang, name[0])
results = getByName(lang[0], name[0], page)
} else if len(ingredients) > 0 {
log.Println("getting recipes by ingredient for", lang, ingredients[0])
results = getByIngredients(lang[0], ingredients)
} else {
results = getMostVisited(lang[0], page)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(results) == 0 {
http.Error(w, "", http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(results)
}
func staticHandler(w http.ResponseWriter, req *http.Request) {
log.Println("received request for", req.URL.Path)
path := req.URL.Path[1:]
if path == "" {
path = "index.html"
}
ext := mime.TypeByExtension(path[strings.LastIndex(path, "."):])
w.Header()["Content-Type"] = []string{ext}
// Add recipes
var data interface{}
var err error
lang := "pt"
if req.Host == "en.feitaemcasa.com" {
lang = "en"
}
switch path {
case "index.html":
by := req.URL.Query()["by"]
search, ok := req.URL.Query()["search"]
if !ok && len(by) > 0 {
http.Error(w, "need a query for "+by[0], http.StatusBadRequest)
return
}
pg := req.URL.Query()["page"]
if len(pg) == 0 {
pg = []string{"0"}
}
page, _ := strconv.Atoi(pg[0])
// The query part
next := page
var results []recipe
if len(by) > 0 {
switch by[0] {
case "name":
log.Println("getting recipes by name for", lang, search)
results = getByName(lang, search[0], page)
case "ingredients":
log.Println("getting recipes by ingredient for", lang, search)
results = getByIngredients(lang, search)
case "visits":
default:
http.Error(w, "unknown search type", http.StatusBadRequest)
return
}
}
if err != nil {
log.Println("error getting recipes", by, search, err)
}
data = struct {
Recipes []recipe
Page int
Prev int
Next int
}{
Recipes: results,
Page: page,
Prev: page - 1,
Next: next,
}
case "recipe.html":
title := req.URL.Query()["title"]
log.Println("getting recipe", title, "language", lang)
if len(title) == 0 {
http.Error(w, "need a title", http.StatusBadRequest)
return
}
data = getRecipe(lang, title[0])
if err != nil {
// TODO: Send nice page with error
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
if lang == "pt" {
path = strings.ReplaceAll(path, ".html", "-pt.html")
}
err = pageTemplate.ExecuteTemplate(w, path, data)
if err != nil {
log.Println(err.Error())
return
}
}
func uploadHandler(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
http.Error(w, "wrong method", http.StatusBadRequest)
return
}
err := req.ParseMultipartForm(100000)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Validation
lang := "pt"
if req.Host == "en.feitaemcasa.com" {
lang = "en"
}
category := req.MultipartForm.Value["category"]
title := req.MultipartForm.Value["title"]
author := req.MultipartForm.Value["author"]
time := req.MultipartForm.Value["time"]
servings := req.MultipartForm.Value["servings"]
if len(category)+len(title)+len(author) < 3 {
http.Error(w, "missing required fields", http.StatusBadRequest)
return
}
const baseURL = "feitaemcasa.com/recipe.html?title="
newRecipe := recipe{
Category: category[0],
Title: title[0],
Author: author[0],
Time: time[0],
Servings: servings[0],
Source: "Feita em casa",
URL: baseURL + url.QueryEscape(title[0]),
Language: lang,
}
path := "upload-pt.html"
if lang == "en" {
newRecipe.Source = "Homemade Recipes"
path = "upload.html"
}
ingredients := req.MultipartForm.Value["ingredients"]
instructions := req.MultipartForm.Value["instructions"]
if len(ingredients[0])+len(instructions[0]) < 2 {
err = fmt.Errorf("ingredients and instructions must not be empty")
pageTemplate.ExecuteTemplate(w, path, err)
return
}
ingredients[0] = strings.TrimSpace(ingredients[0])
instructions[0] = strings.TrimSpace(instructions[0])
newRecipe.Ingredients = strings.Split(ingredients[0], "\n")
newRecipe.Instructions = strings.Split(instructions[0], "\n")
notes := req.MultipartForm.Value["notes"]
if len(notes) > 0 {
notes[0] = strings.TrimSpace(notes[0])
newRecipe.Notes = strings.Split(notes[0], "\n")
}
// Get the picture
for _, file := range req.MultipartForm.File {
picture, _ := file[0].Open()
content := make([]byte, file[0].Size)
_, err = picture.Read(content)
if err != nil {
pageTemplate.ExecuteTemplate(w, path, err)
return
}
// Encode base64
newRecipe.Picture = base64.RawStdEncoding.EncodeToString(content)
}
// Create issue on github
payload, err := json.Marshal(newRecipe)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
body := struct {
Title string `json:"title"`
Body string `json:"body"`
}{
Title: "New recipe: " + newRecipe.Title,
Body: string(payload),
}
bodyBytes, err := json.Marshal(body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
issueReq, err := http.NewRequest(
http.MethodPost,
"https://api.github.com/repos/homemade-recipes/back-end/issues",
bytes.NewReader(bodyBytes),
)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
issueReq.Header.Set("Accept", "application/vnd.github.v3+json")
issueReq.SetBasicAuth("blmayer", githubToken)
res, err := http.DefaultClient.Do(issueReq)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if res.StatusCode > 299 {
var resBody []byte
res.Body.Read(resBody)
http.Error(w, string(resBody), http.StatusInternalServerError)
return
}
// Return html
err = pageTemplate.ExecuteTemplate(w, path, err)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}