From 473052ed8f2c83052ed5b47a7f4cec68ac2621a6 Mon Sep 17 00:00:00 2001 From: xengineering Date: Sun, 13 Oct 2024 19:52:28 +0200 Subject: model: Replace global db variable by custom type Reducing global variables makes it easier to understand functions independently of the rest of the code. Adding the new model.DB type as a custom variant of the sql.DB type makes it possible to write methods for the database which makes the code way more readable. --- view/recipe.go | 72 ++++++++++++++++++++++++++++++---------------------------- 1 file changed, 37 insertions(+), 35 deletions(-) (limited to 'view/recipe.go') diff --git a/view/recipe.go b/view/recipe.go index d77d771..0578107 100644 --- a/view/recipe.go +++ b/view/recipe.go @@ -8,47 +8,49 @@ import ( "github.com/gorilla/mux" ) -func RecipeRead(w http.ResponseWriter, r *http.Request) { - recipe := model.Recipe{} - recipe.Id = mux.Vars(r)[`id`] - - var obj model.Object = &recipe - err := model.Transaction(obj.Read) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } +func RecipeRead(db *model.DB) func(http.ResponseWriter, *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + recipe := model.Recipe{} + recipe.Id = mux.Vars(r)[`id`] - template := "recipe" - view, ok := r.URL.Query()["view"] - if ok { - if len(view) > 1 { - http.Error(w, "More than one 'view' parameter given in URL", http.StatusBadRequest) + var obj model.Object = &recipe + err := db.Transaction(obj.Read) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) return } - template = view[0] - } - is_valid := false - valid_templates := []string{ - "recipe", - "recipe-edit", - "recipe-confirm-deletion", - } - for _, v := range valid_templates { - if template == v { - is_valid = true + template := "recipe" + view, ok := r.URL.Query()["view"] + if ok { + if len(view) > 1 { + http.Error(w, "More than one 'view' parameter given in URL", http.StatusBadRequest) + return + } + template = view[0] } - } - if !is_valid { - http.Error(w, "Unsupported view: "+template, http.StatusBadRequest) - return - } - err = html.ExecuteTemplate(w, template, recipe) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return + is_valid := false + valid_templates := []string{ + "recipe", + "recipe-edit", + "recipe-confirm-deletion", + } + for _, v := range valid_templates { + if template == v { + is_valid = true + } + } + if !is_valid { + http.Error(w, "Unsupported view: "+template, http.StatusBadRequest) + return + } + + err = html.ExecuteTemplate(w, template, recipe) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } } } -- cgit v1.2.3-70-g09d2