package handlers import ( "html/template" "mealprep/database" "net/http" "strconv" "strings" ) // IngredientsHandler handles the ingredients page func IngredientsHandler(w http.ResponseWriter, r *http.Request) { ingredients, err := database.GetAllIngredients() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tmpl := `

Ingredients

{{range .}}
{{.Name}} ({{.Unit}})
{{end}}
` t := template.Must(template.New("ingredients").Parse(tmpl)) t.Execute(w, ingredients) } // AddIngredientHandler handles adding a new ingredient func AddIngredientHandler(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } name := strings.TrimSpace(r.FormValue("name")) unit := strings.TrimSpace(r.FormValue("unit")) if name == "" || unit == "" { http.Error(w, "Name and unit are required", http.StatusBadRequest) return } id, err := database.AddIngredient(name, unit) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tmpl := `
{{.Name}} ({{.Unit}})
` data := struct { ID int64 Name string Unit string }{id, name, unit} t := template.Must(template.New("ingredient").Parse(tmpl)) t.Execute(w, data) } // DeleteIngredientHandler handles deleting an ingredient func DeleteIngredientHandler(w http.ResponseWriter, r *http.Request) { idStr := strings.TrimPrefix(r.URL.Path, "/ingredients/") id, err := strconv.Atoi(idStr) if err != nil { http.Error(w, "Invalid ID", http.StatusBadRequest) return } if err := database.DeleteIngredient(id); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) }