-
Notifications
You must be signed in to change notification settings - Fork 2
/
recipe.go
442 lines (373 loc) · 11.4 KB
/
recipe.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package routers
import (
"errors"
"fmt"
"io/ioutil"
"log"
"math"
"mime/multipart"
"net/http"
"strconv"
"github.com/chadweimer/gomp/models"
"github.com/julienschmidt/httprouter"
"github.com/mholt/binding"
)
// RecipeForm encapsulates user input on the Create and Edit recipe screens
type RecipeForm struct {
Name string `form:"name"`
ServingSize string `form:"serving-size"`
NutritionInfo string `form:"nutrition-info"`
Ingredients string `form:"ingredients"`
Directions string `form:"directions"`
Tags []string `form:"tags"`
}
// FieldMap provides the RecipeForm field name maping for form binding
func (f *RecipeForm) FieldMap(req *http.Request) binding.FieldMap {
return binding.FieldMap{
&f.Name: "name",
&f.ServingSize: "serving-size",
&f.NutritionInfo: "nutrition-info",
&f.Ingredients: "ingredients",
&f.Directions: "directions",
&f.Tags: "tags",
}
}
// NoteForm encapsulates user input for a note on a recipe
type NoteForm struct {
Note string `form:"note"`
}
// FieldMap provides the NoteForm field name maping for form binding
func (f *NoteForm) FieldMap(req *http.Request) binding.FieldMap {
return binding.FieldMap{
&f.Note: "note",
}
}
// AttachmentForm encapsulates user input for attaching a file (image) to a recipe
type AttachmentForm struct {
FileName string `form:"file_name"`
FileContent *multipart.FileHeader `form:"file_content"`
}
// FieldMap provides the AttachmentForm field name maping for form binding
func (f *AttachmentForm) FieldMap(req *http.Request) binding.FieldMap {
return binding.FieldMap{
&f.FileName: "file_name",
&f.FileContent: "file_content",
}
}
// RatingForm encapsulates user input for rating a recipe (1-5)
type RatingForm struct {
Rating float64 `form:"rating"`
}
// FieldMap provides the RatingForm field name maping for form binding
func (f *RatingForm) FieldMap(req *http.Request) binding.FieldMap {
return binding.FieldMap{
&f.Rating: "rating",
}
}
// GetRecipe handles retrieving and rendering a single recipe
func (rc *RouteController) GetRecipe(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
id, err := strconv.ParseInt(p.ByName("id"), 10, 64)
if rc.HasError(resp, err) {
return
}
recipe, err := rc.model.Recipes.Read(id)
if err == models.ErrNotFound {
rc.NotFound(resp, req)
return
}
if rc.HasError(resp, err) {
return
}
notes, err := rc.model.Notes.List(id)
if rc.HasError(resp, err) {
return
}
imgs, err := rc.model.Images.List(id)
if rc.HasError(resp, err) {
return
}
data := map[string]interface{}{
"Recipe": recipe,
"Notes": notes,
"Images": imgs,
}
rc.HTML(resp, http.StatusOK, "recipe/view", data)
}
// ListRecipes handles retrieving and rending a list of available recipes
func (rc *RouteController) ListRecipes(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
sess, err := rc.sessionStore.Get(req, "UserSession")
if err != nil {
log.Print("Invalid session retrieved.")
http.Redirect(resp, req, fmt.Sprintf("%s/logout", rc.cfg.RootURLPath), http.StatusFound)
return
}
clear := req.URL.Query().Get("clear")
if clear != "" {
delete(sess.Values, "q")
sess.Save(req, resp)
http.Redirect(resp, req, fmt.Sprintf("%s/recipes", rc.cfg.RootURLPath), http.StatusFound)
return
}
query := req.URL.Query().Get("q")
if query == "" {
if sessQuery := sess.Values["q"]; sessQuery != nil {
query = sessQuery.(string)
}
}
var page int64
if pageStr := req.URL.Query().Get("page"); pageStr != "" {
page, _ = strconv.ParseInt(pageStr, 10, 64)
}
if page < 1 {
page = 1
}
viewType := req.URL.Query().Get("view")
if viewType == "" {
viewType = "full"
if sessViewType := sess.Values["view"]; sessViewType != nil {
viewType = sessViewType.(string)
}
}
var count int64
if viewType == "compact" {
count = 60
} else {
count = 12
}
var recipes *models.Recipes
var total int64
if query == "" {
recipes, total, err = rc.model.Recipes.List(page, count)
} else {
recipes, total, err = rc.model.Recipes.Find(query, page, count)
}
if rc.HasError(resp, err) {
return
}
sess.Values["q"] = query
sess.Values["view"] = viewType
sess.Save(req, resp)
data := map[string]interface{}{
"Query": query,
"PageNum": page,
"PerPage": count,
"NumPages": int64(math.Ceil(float64(total) / float64(count))),
"Recipes": recipes,
"SearchQuery": query,
"ResultCount": total,
"ViewType": viewType,
}
rc.HTML(resp, http.StatusOK, "recipe/list", data)
}
// CreateRecipe handles rendering the create recipe screen
func (rc *RouteController) CreateRecipe(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
rc.HTML(resp, http.StatusOK, "recipe/create", make(map[string]interface{}))
}
// CreateRecipePost handles processing the supplied form input from the create recipe screen
func (rc *RouteController) CreateRecipePost(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
form := new(RecipeForm)
errs := binding.Bind(req, form)
if errs != nil && errs.Len() > 0 {
rc.HasError(resp, errors.New(errs.Error()))
return
}
recipe := &models.Recipe{
Name: form.Name,
ServingSize: form.ServingSize,
NutritionInfo: form.NutritionInfo,
Ingredients: form.Ingredients,
Directions: form.Directions,
Tags: form.Tags,
}
err := rc.model.Recipes.Create(recipe)
if rc.HasError(resp, err) {
return
}
http.Redirect(resp, req, fmt.Sprintf("%s/recipes/%d", rc.cfg.RootURLPath, recipe.ID), http.StatusFound)
}
// EditRecipe handles rendering the edit recipe screen
func (rc *RouteController) EditRecipe(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
id, err := strconv.ParseInt(p.ByName("id"), 10, 64)
if rc.HasError(resp, err) {
return
}
recipe, err := rc.model.Recipes.Read(id)
if err == models.ErrNotFound {
rc.NotFound(resp, req)
return
}
if rc.HasError(resp, err) {
return
}
data := map[string]interface{}{
"Recipe": recipe,
}
rc.HTML(resp, http.StatusOK, "recipe/edit", data)
}
// EditRecipePost handles processing the supplied form input from the edit recipe screen
func (rc *RouteController) EditRecipePost(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
form := new(RecipeForm)
errs := binding.Bind(req, form)
if errs != nil && errs.Len() > 0 {
rc.HasError(resp, errors.New(errs.Error()))
return
}
id, err := strconv.ParseInt(p.ByName("id"), 10, 64)
if rc.HasError(resp, err) {
return
}
recipe := &models.Recipe{
ID: id,
Name: form.Name,
ServingSize: form.ServingSize,
NutritionInfo: form.NutritionInfo,
Ingredients: form.Ingredients,
Directions: form.Directions,
Tags: form.Tags,
}
err = rc.model.Recipes.Update(recipe)
if rc.HasError(resp, err) {
return
}
http.Redirect(resp, req, fmt.Sprintf("%s/recipes/%d", rc.cfg.RootURLPath, id), http.StatusFound)
}
// DeleteRecipe handles deleting the recipe with the given id
func (rc *RouteController) DeleteRecipe(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
id, err := strconv.ParseInt(p.ByName("id"), 10, 64)
if rc.HasError(resp, err) {
return
}
err = rc.model.Recipes.Delete(id)
if rc.HasError(resp, err) {
return
}
// If we successfully deleted the recipe, delete all of it's attachments
err = rc.model.Images.DeleteAll(id)
if rc.HasError(resp, err) {
return
}
http.Redirect(resp, req, fmt.Sprintf("%s/recipes", rc.cfg.RootURLPath), http.StatusFound)
}
// CreateAttachmentPost handles uploading the specified attachment (image) to a recipe
func (rc *RouteController) CreateAttachmentPost(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
form := new(AttachmentForm)
errs := binding.Bind(req, form)
if errs != nil && errs.Len() > 0 {
rc.HasError(resp, errors.New(errs.Error()))
return
}
id, err := strconv.ParseInt(p.ByName("id"), 10, 64)
if rc.HasError(resp, err) {
return
}
uploadedFile, err := form.FileContent.Open()
if rc.HasError(resp, err) {
return
}
defer uploadedFile.Close()
uploadedFileData, err := ioutil.ReadAll(uploadedFile)
if rc.HasError(resp, err) {
return
}
err = rc.model.Images.Save(id, form.FileName, uploadedFileData)
if rc.HasError(resp, err) {
return
}
http.Redirect(resp, req, fmt.Sprintf("%s/recipes/%d", rc.cfg.RootURLPath, id), http.StatusFound)
}
// DeleteAttachment handles deleting the specified attachment (image) from a recipe
func (rc *RouteController) DeleteAttachment(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
name := p.ByName("name")
id, err := strconv.ParseInt(p.ByName("id"), 10, 64)
if rc.HasError(resp, err) {
return
}
err = rc.model.Images.Delete(id, name)
if rc.HasError(resp, err) {
return
}
http.Redirect(resp, req, fmt.Sprintf("%s/recipes/%d", rc.cfg.RootURLPath, id), http.StatusFound)
}
// CreateNotePost handles processing the supplied form input for adding a note to a recipe
func (rc *RouteController) CreateNotePost(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
form := new(NoteForm)
errs := binding.Bind(req, form)
if errs != nil && errs.Len() > 0 {
rc.HasError(resp, errors.New(errs.Error()))
return
}
id, err := strconv.ParseInt(p.ByName("id"), 10, 64)
if rc.HasError(resp, err) {
return
}
note := &models.Note{
RecipeID: id,
Note: form.Note,
}
err = rc.model.Notes.Create(note)
if rc.HasError(resp, err) {
return
}
http.Redirect(resp, req, fmt.Sprintf("%s/recipes/%d", rc.cfg.RootURLPath, id), http.StatusFound)
}
// EditNotePost handles processing the supplied form input for adding a note to a recipe
func (rc *RouteController) EditNotePost(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
form := new(NoteForm)
errs := binding.Bind(req, form)
if errs != nil && errs.Len() > 0 {
rc.HasError(resp, errors.New(errs.Error()))
return
}
id, err := strconv.ParseInt(p.ByName("id"), 10, 64)
if rc.HasError(resp, err) {
return
}
noteID, err := strconv.ParseInt(p.ByName("note_id"), 10, 64)
if rc.HasError(resp, err) {
return
}
note := &models.Note{
ID: noteID,
RecipeID: id,
Note: form.Note,
}
err = rc.model.Notes.Update(note)
if rc.HasError(resp, err) {
return
}
http.Redirect(resp, req, fmt.Sprintf("%s/recipes/%d", rc.cfg.RootURLPath, id), http.StatusFound)
}
// DeleteNote handles deleting the note with the given id
func (rc *RouteController) DeleteNote(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
id, err := strconv.ParseInt(p.ByName("id"), 10, 64)
if rc.HasError(resp, err) {
return
}
noteID, err := strconv.ParseInt(p.ByName("note_id"), 10, 64)
if rc.HasError(resp, err) {
return
}
err = rc.model.Notes.Delete(noteID)
if rc.HasError(resp, err) {
return
}
http.Redirect(resp, req, fmt.Sprintf("%s/recipes/%d", rc.cfg.RootURLPath, id), http.StatusFound)
}
// RateRecipePost handles adding/updating the rating of a recipe
func (rc *RouteController) RateRecipePost(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
form := new(RatingForm)
errs := binding.Bind(req, form)
if errs != nil && errs.Len() > 0 {
rc.HasError(resp, errors.New(errs.Error()))
return
}
id, err := strconv.ParseInt(p.ByName("id"), 10, 64)
if rc.HasError(resp, err) {
return
}
err = rc.model.Recipes.SetRating(id, form.Rating)
if rc.HasError(resp, err) {
return
}
http.Redirect(resp, req, fmt.Sprintf("%s/recipes/%d", rc.cfg.RootURLPath, id), http.StatusFound)
}