+56
service/spotify/playlists.go
+56
service/spotify/playlists.go
···
1
+
package spotify
2
+
3
+
import (
4
+
"encoding/json"
5
+
"fmt"
6
+
"io"
7
+
"log"
8
+
"net/http"
9
+
)
10
+
11
+
type Playlist struct {
12
+
Name string `json:"name"`
13
+
ID string `json:"id"`
14
+
}
15
+
16
+
type PlaylistResponse struct {
17
+
Limit int `json:"limit"`
18
+
Next string `json:"next"`
19
+
Offset int `json:"offset"`
20
+
Previous string `json:"previous"`
21
+
Total int `json:"total"`
22
+
Items []Playlist `json:"items"`
23
+
}
24
+
25
+
func (s *SpotifyService) getUserPlaylists(userID int64) (*PlaylistResponse, error) {
26
+
27
+
s.mu.RLock()
28
+
token, exists := s.userTokens[userID]
29
+
s.mu.RUnlock()
30
+
31
+
if !exists || token == "" {
32
+
return nil, fmt.Errorf("no access token for user %d", userID)
33
+
}
34
+
35
+
resp, err := http.NewRequest("GET", "https://api.spotify.com/v1/me/playlists", nil)
36
+
if err != nil {
37
+
return nil, fmt.Errorf("failed to get user playlists: %w", err)
38
+
}
39
+
defer resp.Body.Close()
40
+
41
+
if resp.Response.StatusCode != http.StatusOK {
42
+
return nil, fmt.Errorf("error response from Spotify: %s", resp.Response.Status)
43
+
}
44
+
body, err := io.ReadAll(resp.Body)
45
+
if err != nil {
46
+
log.Fatal("failed to read resp.Body")
47
+
}
48
+
49
+
var playlistResponse PlaylistResponse
50
+
51
+
if err := json.Unmarshal(body, &playlistResponse); err != nil {
52
+
return nil, fmt.Errorf("failed to decode user playlists: %w", err)
53
+
}
54
+
55
+
return &playlistResponse, nil
56
+
}