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)

25
views/item.html Normal file
View File

@@ -0,0 +1,25 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{.Item.Title}}</title>
<style>
.container {
max-width: 1200px;
width: 100%;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<img src="{{.Item.Image}}" alt="" width="auto" height="100px" />
<h2>{{.Item.Title}}</h2>
<form method="POST" action="/items/{{.Item.ID}}/delete">
<button type="submit">Delete item</button>
</form>
</div>
</body>
</html>