add page for item and route for deleting items

This commit is contained in:
2026-02-19 15:42:42 +03:00
parent 7049c22988
commit 505a8c1407
2 changed files with 67 additions and 0 deletions

42
main.go
View File

@@ -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)