Skip to content

Commit 3a0f6e4

Browse files
committed
added song cache
1 parent cabf443 commit 3a0f6e4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

music.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"encoding/json"
55
"os/exec"
6+
"sync"
67
)
78

89
// Song : Song information fetched from youtube-dl. More fields exist in the JSON response, but this is what we need.
@@ -13,7 +14,43 @@ type Song struct {
1314
WebpageURL string `json:"webpage_url"`
1415
}
1516

17+
type SongCache struct {
18+
cache map[string]Song
19+
mux sync.RWMutex
20+
}
21+
22+
var songCache = SongCache{
23+
cache: make(map[string]Song),
24+
}
25+
26+
func (sc *SongCache) Get(url string) (Song, bool) {
27+
sc.mux.RLock()
28+
defer sc.mux.RUnlock()
29+
song, exists := sc.cache[url]
30+
return song, exists
31+
}
32+
33+
func (sc *SongCache) Set(url string, song Song) {
34+
sc.mux.Lock()
35+
defer sc.mux.Unlock()
36+
sc.cache[url] = song
37+
}
38+
1639
func fetchSong(url string) (Song, error) {
40+
// Check cache first
41+
if song, exists := songCache.Get(url); exists {
42+
return song, nil
43+
}
44+
45+
// If not in cache, fetch and store
46+
song, err := fetchSongFromYoutubeDL(url)
47+
if err == nil {
48+
songCache.Set(url, song)
49+
}
50+
return song, err
51+
}
52+
53+
func fetchSongFromYoutubeDL(url string) (Song, error) {
1754
// Maybe make this function return a promise or something in the future
1855
var songData Song
1956
// JSON dump has no extra overhead, and we get more info that we need that might be useful

0 commit comments

Comments
 (0)