gomusic/utils.go

70 lines
1.8 KiB
Go

package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
type SpotifyResponse struct {
ID string
Name string
Popularity int
Genres []string
}
type ResponseError struct {
StatusCode int
Err error
}
func (r ResponseError) Error() string {
return fmt.Sprintf("Response error with status code: %d, error: %v", r.StatusCode, r.Err)
}
// Makes a request to spotify API to grab artist data
// And parse the results into a properly typed struct
func getSpotifyArtistData(artistID string, spotifyAuthToken string) (SpotifyResponse, error) {
artistEndpoint := fmt.Sprintf("https://api.spotify.com/v1/artists/%s", artistID)
req, err := http.NewRequest("GET", artistEndpoint, nil)
if err != nil {
respErr := &ResponseError{
StatusCode: 500,
Err: errors.New("Failed to build request"),
}
return SpotifyResponse{}, respErr
}
req.Header.Add("Authorization", spotifyAuthToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
respErr := &ResponseError{
StatusCode: 500,
Err: errors.New("Failed to send request to spotify"),
}
return SpotifyResponse{}, respErr
} else if resp.StatusCode != 200 {
respErr := &ResponseError{
StatusCode: resp.StatusCode,
Err: errors.New("Failed to get artist data from spotify API"),
}
return SpotifyResponse{}, respErr
}
defer resp.Body.Close()
var spotifyResponse SpotifyResponse
err = json.NewDecoder(resp.Body).Decode(&spotifyResponse)
if err != nil {
respErr := &ResponseError{
StatusCode: 500,
Err: errors.New("Failed to decode response body"),
}
return SpotifyResponse{}, respErr
}
// After all the above checks we assume this response is populated
// If errors arise we can do extra validation here
return spotifyResponse, nil
}