From 76b550d628883a080c7789362310bcda5a5dde9e Mon Sep 17 00:00:00 2001 From: Daniil Tsivinsky Date: Fri, 13 Feb 2026 15:16:05 +0300 Subject: [PATCH] add api route to delete podcasts --- main.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/main.go b/main.go index 8a8f925..f30fbd9 100644 --- a/main.go +++ b/main.go @@ -128,6 +128,20 @@ func getPodcasts(db *sqlx.DB) ([]*Podcast, error) { return podcasts, nil } +func getPodcastById(db *sqlx.DB, podcastId int64) (*Podcast, error) { + row := db.QueryRowx("SELECT * FROM podcasts WHERE id = ?", podcastId) + if row.Err() != nil { + return nil, fmt.Errorf("failed to query db: %v", row.Err()) + } + + podcast := new(Podcast) + if err := row.StructScan(podcast); err != nil { + return nil, fmt.Errorf("failed to scan struct podcast: %v", err) + } + + return podcast, nil +} + func createPodcast(db *sqlx.DB, feed RSSFeed, feedUrl string) error { _, err := db.NamedExec("INSERT INTO podcasts (name, description, feed, language, link, image) VALUES (:name, :description, :feed, :language, :link, :image)", map[string]any{ "name": feed.Channel.Title, @@ -199,6 +213,16 @@ func getPodcastEpisodes(db *sqlx.DB, podcastId int64) ([]*Episode, error) { return episodes, nil } +func deletePodcastById(db *sqlx.DB, podcastId int64) error { + if _, err := db.NamedExec("DELETE FROM episodes WHERE podcast_id = :podcastId; DELETE FROM podcasts WHERE id = :podcastId", map[string]any{ + "podcastId": podcastId, + }); err != nil { + return fmt.Errorf("failed to delete podcasts and episodes: %v", err) + } + + return nil +} + func main() { podcastsDirPath := os.Getenv("PODCASTS_DIRPATH") @@ -360,6 +384,34 @@ func main() { sendJSON(w, episodes, 200) }) + mux.HandleFunc("DELETE /podcasts/{id}", func(w http.ResponseWriter, r *http.Request) { + id, err := strconv.Atoi(r.PathValue("id")) + if err != nil { + http.Error(w, err.Error(), 404) + return + } + + podcast, err := getPodcastById(db, int64(id)) + if err != nil { + http.Error(w, err.Error(), 404) + return + } + + if err := os.RemoveAll(path.Join(podcastsDirPath, podcast.Name)); err != nil { + http.Error(w, err.Error(), 404) + return + } + + if err := deletePodcastById(db, int64(id)); err != nil { + http.Error(w, err.Error(), 404) + return + } + + sendJSON(w, struct { + Ok bool `json:"ok"` + }{true}, 200) + }) + fmt.Println("starting http server on http://localhost:5000") if err := http.ListenAndServe(":5000", mux); err != nil { log.Fatalf("failed to start http server: %v\n", err)