-
Notifications
You must be signed in to change notification settings - Fork 0
/
radiolist.go
84 lines (69 loc) · 2.29 KB
/
radiolist.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"encoding/json"
"github.com/joarleth/spotify/track"
"net/http"
"net/url"
"reflect"
"strings"
)
type searchParameters struct {
title string
artist string
album string
}
type searcherInterface interface {
FindClosestMatch(string, string, string) (track.Track, error)
}
func spotifySearchHandler(w http.ResponseWriter, r *http.Request) {
s := track.NewSearcher("se")
title, artist, album := getSearchParameters(r.URL)
spotifySearchHelper(w, s, title, artist, album)
}
func spotifySearchHelper(w http.ResponseWriter, s searcherInterface, title, artist, album string) {
t, err := s.FindClosestMatch(title, artist, album)
if err != nil {
if terr, isTrackError := err.(track.TrackError); isTrackError {
switch terr.ErrorType {
case track.ArgumentError:
http.Error(w, "Bad Request: title and at least one of artist and album must be passed as query parameters.", http.StatusBadRequest)
return
case track.UnexpectedError:
http.Error(w, "Internal Server Error: An unexpected error occurred.", http.StatusInternalServerError)
return
case track.RateLimitError:
http.Error(w, "Service Unavailable: Too many requests to spotify at this time. Please come back another time.", http.StatusServiceUnavailable)
return
case track.ExternalServiceError:
http.Error(w, "Service Unavailable: The Spotify service used by this API bahaves unexpectedly.", http.StatusServiceUnavailable)
return
}
}
http.Error(w, "Internal Server Error: This should never happen.", http.StatusInternalServerError)
return
}
if reflect.DeepEqual(t, track.Track{}) {
http.Error(w, "Not Found: Couldn't find a track matching your query.", http.StatusNotFound)
return
}
json_result, merr := json.Marshal(t)
if merr != nil {
http.Error(w, "Internal Server Error: Unable to serialize track.", http.StatusInternalServerError)
return
}
w.Write(json_result)
}
func getSearchParameters(url *url.URL) (title string, artist string, album string) {
queries := url.Query()
title = queries.Get("title")
artist = queries.Get("artist")
album = queries.Get("album")
title = strings.TrimSpace(title)
artist = strings.TrimSpace(artist)
album = strings.TrimSpace(album)
return
}
func main() {
http.HandleFunc("/", spotifySearchHandler)
http.ListenAndServe(":8080", nil)
}