From 3e7a3a2f3b1a3ae59d9b22cc0ff463ddcbd96e35 Mon Sep 17 00:00:00 2001 From: Justin Hawkins Date: Fri, 10 Mar 2023 00:07:29 +1030 Subject: [PATCH] Fix some more races --- download/download.go | 13 +++++++++++++ main.go | 11 ++++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/download/download.go b/download/download.go index b271018..b997e70 100644 --- a/download/download.go +++ b/download/download.go @@ -1,6 +1,7 @@ package download import ( + "encoding/json" "fmt" "io" "log" @@ -61,6 +62,18 @@ func (m *Manager) ManageQueue() { } } +func (m *Manager) DownloadsAsJSON() ([]byte, error) { + + m.Lock.Lock() + defer m.Lock.Unlock() + for _, dl := range m.Downloads { + dl.Lock.Lock() + defer dl.Lock.Unlock() + } + b, err := json.Marshal(m.Downloads) + return b, err +} + // startQueued starts any downloads that have been queued, we would not exceed // maxRunning. If maxRunning is 0, there is no limit. func (m *Manager) startQueued(maxRunning int) { diff --git a/main.go b/main.go index bdf5877..8437b03 100644 --- a/main.go +++ b/main.go @@ -327,7 +327,11 @@ func fetchInfoOneRESTHandler(w http.ResponseWriter, r *http.Request) { } // just a get, return the object + thisDownload.Lock.Lock() + defer thisDownload.Lock.Unlock() + b, _ := json.Marshal(thisDownload) + w.Write(b) return } else { @@ -337,9 +341,10 @@ func fetchInfoOneRESTHandler(w http.ResponseWriter, r *http.Request) { func fetchInfoRESTHandler(w http.ResponseWriter, r *http.Request) { - dm.Lock.Lock() - defer dm.Lock.Unlock() - b, _ := json.Marshal(dm.Downloads) + b, err := dm.DownloadsAsJSON() + if err != nil { + panic(err) + } w.Write(b) }