Handle misssed errors for encoding and decoding feeds

This commit is contained in:
Jason Streifling 2024-02-18 14:31:28 +01:00
parent 171a0dd250
commit 75a0af055c
2 changed files with 20 additions and 12 deletions

View File

@ -26,27 +26,32 @@ func NewFeed(title, link, desc string) *Feed {
func SaveFeed(feed *Feed, filename string) error {
file, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error cmd/feed/rss.go WriteFeed os.Create(): %v", err)
return fmt.Errorf("error cmd/feed/rss.go SaveFeed os.Create(): %v", err)
}
defer file.Close()
encoder := gob.NewEncoder(file)
encoder.Encode(feed)
err = encoder.Encode(feed)
if err != nil {
return fmt.Errorf("error cmd/feed/rss.go SaveFeed encoder.Encode(): %v", err)
}
return nil
}
func OpenFeed(filename string) (*Feed, error) {
var feed *Feed
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("error cmd/feed/rss.go ReadFeed os.Open(): %v", err)
return nil, fmt.Errorf("error cmd/feed/rss.go OpenFeed os.Open(): %v", err)
}
defer file.Close()
feed := &Feed{}
decoder := gob.NewDecoder(file)
decoder.Decode(feed)
err = decoder.Decode(feed)
if err != nil {
return nil, fmt.Errorf("error cmd/feed/rss.go OpenFeed decoder.Decode(): %v", err)
}
return feed, nil
}

15
main.go
View File

@ -10,17 +10,20 @@ import (
)
func main() {
mux := http.NewServeMux()
feed := feed.NewFeed("Freimaurer Distrikt Niedersachsen und Sachsen-Anhalt",
"https://distrikt-ni-st.de",
"Freiheit, Gleichheit, Brüderlichkeit, Toleranz und Humanität")
f, err := feed.OpenFeed("tmp/rss.gob")
if err != nil {
log.Println(err)
f = feed.NewFeed("Freimaurer Distrikt Niedersachsen und Sachsen-Anhalt",
"https://distrikt-ni-st.de",
"Freiheit, Gleichheit, Brüderlichkeit, Toleranz und Humanität")
}
mux := http.NewServeMux()
mux.Handle("/web/static/", http.StripPrefix("/web/static/", http.FileServer(http.Dir("web/static/"))))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
template.Must(template.ParseFiles("web/templates/index.html", "web/templates/editor.html")).Execute(w, nil)
})
mux.HandleFunc("POST /finished-edit/", handlers.HandleFinishedEdit(feed))
mux.HandleFunc("POST /finished-edit/", handlers.HandleFinishedEdit(f))
log.Fatalln(http.ListenAndServe(":8080", mux))
}