From 924245e9c9386d2e78fbe24c3818fc2a53be6364 Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Wed, 30 Mar 2022 19:13:55 +0400 Subject: [PATCH] A little refactor. Better errors handling. --- internal/handlers/handlers.go | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go index 126fee4..3fa2ddf 100644 --- a/internal/handlers/handlers.go +++ b/internal/handlers/handlers.go @@ -52,38 +52,45 @@ func (h *RadioHandlers) AssetsFS() http.FileSystem { } func (h *RadioHandlers) Index(w http.ResponseWriter, r *http.Request) { - rad, err := radio.IcecastGetStatus(h.conf.Icecast.URL) + status, err := radio.IcecastGetStatus(h.conf.Icecast.URL) if err != nil { h.logErr.Println("failed to get Icecast status:", err) - rad = &radio.IcecastStatus{} + status = &radio.IcecastStatus{} + return } if err := compiledTemplates["index"].Execute(w, &IndexData{ MainSite: utils.MainSite(r.Host), - Status: rad, + Status: status, Songs: radio.IcecastLastPlayedSongs(h.conf.ListLastNSongs, h.conf.Icecast.Playlist), }); err != nil { - w.WriteHeader(http.StatusInternalServerError) h.logErr.Fatalln("failed to execute Index template:", err) + http.Error(w, "cannot execute Index template", http.StatusInternalServerError) } } -func (h *RadioHandlers) Stats(w http.ResponseWriter, r *http.Request) { - st, err := radio.IcecastGetStatus(h.conf.Icecast.URL) +func (h *RadioHandlers) Stats(w http.ResponseWriter, _ *http.Request) { + status, err := radio.IcecastGetStatus(h.conf.Icecast.URL) if err != nil { - st = &radio.IcecastStatus{} + h.logErr.Println("cannot retrieve Icecast status:", err) + http.Error(w, "cannot retrieve Icecast status", http.StatusInternalServerError) + return } - json.NewEncoder(w).Encode(st) + json.NewEncoder(w).Encode(status) } -func (h *RadioHandlers) LastSong(w http.ResponseWriter, r *http.Request) { +func (h *RadioHandlers) LastSong(w http.ResponseWriter, _ *http.Request) { songs := radio.IcecastLastPlayedSongs(1, h.conf.Icecast.Playlist) + if len(songs) == 0 { + w.WriteHeader(http.StatusNotFound) + return + } json.NewEncoder(w).Encode(songs[0]) } -func (h *RadioHandlers) Playlist(w http.ResponseWriter, r *http.Request) { +func (h *RadioHandlers) Playlist(w http.ResponseWriter, _ *http.Request) { w.Header().Add("Content-Disposition", "attachment; filename=\"radio.arav.top.m3u\"") pf, _ := assetsDir.Open("radio.arav.top.m3u")