Improved handling of errors and included manual refreshing
Signed-off-by: Marcus Noble <github@marcusnoble.co.uk>
This commit is contained in:
54
main.go
54
main.go
@@ -28,24 +28,58 @@ func init() {
|
||||
|
||||
func main() {
|
||||
latestBooks := map[string]*storygraph.Book{}
|
||||
go func() {
|
||||
var err error
|
||||
for {
|
||||
latestBooks, err = storygraph.GetLatestBooks()
|
||||
if err != nil {
|
||||
fmt.Println("Error fetching latest books:", err)
|
||||
return
|
||||
refreshingBooks := true
|
||||
var lastUpdated *time.Time
|
||||
|
||||
updateBooks := func() {
|
||||
refreshingBooks = true
|
||||
defer func() { refreshingBooks = false }()
|
||||
newBookList, err := storygraph.GetLatestBooks()
|
||||
if err != nil {
|
||||
fmt.Println("Error fetching latest books:", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Update each category individually with books we have managed to find
|
||||
for cat, book := range newBookList {
|
||||
if b, ok := newBookList[cat]; ok && b != nil {
|
||||
latestBooks[cat] = book
|
||||
}
|
||||
}
|
||||
now := time.Now()
|
||||
lastUpdated = &now
|
||||
fmt.Println("Updated latest book recommendations")
|
||||
}
|
||||
|
||||
fmt.Println("Updated latest book recommendations")
|
||||
|
||||
go func() {
|
||||
for {
|
||||
updateBooks()
|
||||
time.Sleep(1 * time.Hour)
|
||||
}
|
||||
}()
|
||||
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
type data struct {
|
||||
Books map[string]*storygraph.Book
|
||||
LastUpdated string
|
||||
Refreshing bool
|
||||
}
|
||||
d := data{
|
||||
Books: latestBooks,
|
||||
LastUpdated: "",
|
||||
Refreshing: refreshingBooks,
|
||||
}
|
||||
if lastUpdated != nil {
|
||||
d.LastUpdated = lastUpdated.Format(time.RFC1123)
|
||||
}
|
||||
tmpl := template.Must(template.ParseFiles("templates/index.html"))
|
||||
tmpl.Execute(w, latestBooks)
|
||||
tmpl.Execute(w, d)
|
||||
})
|
||||
http.HandleFunc("/refresh", func(w http.ResponseWriter, r *http.Request) {
|
||||
go updateBooks()
|
||||
w.Header().Set("Location", "/")
|
||||
w.Header().Set("Refresh", "0; url=/")
|
||||
w.Write([]byte("Refreshing..."))
|
||||
})
|
||||
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
|
||||
http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
|
||||
|
||||
Reference in New Issue
Block a user