package view import ( "net/http" "sort" "xengineering.eu/ceres/model" ) func RecipeRead(db *model.DB) http.Handler { return http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { var data struct { Recipe model.Recipe HasIngredients bool Summary []model.Ingredient } data.Recipe.Id = r.PathValue("id") var obj model.Object = &data.Recipe err := db.Transaction(obj.Read) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } data.HasIngredients = false for _, step := range data.Recipe.Steps { if len(step.Ingredients) > 0 { data.HasIngredients = true } for _, ingredient := range step.Ingredients { data.Summary = append(data.Summary, ingredient) } } sort.Slice(data.Summary, func(i, j int) bool { return data.Summary[i].Type < data.Summary[j].Type }) 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] } 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, data) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }, ) } func RecipeCreate() http.Handler { return http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { var data struct { Recipe model.Recipe } err := html.ExecuteTemplate(w, "recipe-edit", data) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }, ) }