diff --git a/main.go b/main.go index 46ecc3c..a5a2f7a 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ import ( "log" "net/http" "os" + "strconv" "time" "github.com/PuerkitoBio/goquery" @@ -168,6 +169,47 @@ END; } }) + mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) { + id, err := strconv.Atoi(r.PathValue("id")) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + row := db.QueryRowx("SELECT * FROM items WHERE id = ?", id) + if row.Err() != nil { + http.Error(w, fmt.Sprintf("item not found: %v", row.Err()), 404) + return + } + + item := &Item{} + if err := row.StructScan(item); err != nil { + http.Error(w, fmt.Sprintf("failed to scan item to struct: %v", err), 500) + return + } + + tmpl.ExecuteTemplate(w, "item.html", struct { + Item *Item + }{ + Item: item, + }) + }) + + mux.HandleFunc("POST /items/{id}/delete", func(w http.ResponseWriter, r *http.Request) { + id, err := strconv.Atoi(r.PathValue("id")) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + if _, err := db.Exec("DELETE FROM items WHERE id = ?", id); err != nil { + http.Error(w, fmt.Sprintf("failed to delete item: %v", err), 500) + return + } + + http.Redirect(w, r, "/", http.StatusFound) + }) + log.Println("starting http server") if err := http.ListenAndServe(":5000", mux); err != nil { log.Fatalf("failed to start http server: %v\n", err) diff --git a/views/item.html b/views/item.html new file mode 100644 index 0000000..ef0402a --- /dev/null +++ b/views/item.html @@ -0,0 +1,25 @@ + + + + + + {{.Item.Title}} + + + + +
+ +

{{.Item.Title}}

+
+ +
+
+ +