This repository has been archived by the owner on Sep 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch_tracks.go
69 lines (58 loc) · 1.51 KB
/
search_tracks.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
package audiusclient
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
)
type SearchTracksResponse struct {
Data []APITrack
}
func (c *Client) SearchTracks(query string) (SearchTracksResponse, error) {
var searchTracksResponse SearchTracksResponse
// Select an audius host:
selectedHostURL, err := c.GetHost()
if err != nil {
return searchTracksResponse, err
}
requestURL := *selectedHostURL
requestURL.Path = "/v1/tracks/search"
// Build the query:
values := requestURL.Query()
values.Set("query", query)
requestURL.RawQuery = values.Encode()
// Create the request:
urlString := requestURL.String()
req, err := http.NewRequest("GET", urlString, nil)
if err != nil {
return searchTracksResponse, err
}
// Make the request:
res, err := httpClient.Do(req)
if err != nil {
return searchTracksResponse, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
// Parse the error:
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return searchTracksResponse, err
}
err = errors.New(string(body))
return searchTracksResponse, err
}
// Decode the body:
err = json.NewDecoder(res.Body).Decode(&searchTracksResponse)
if err != nil {
return searchTracksResponse, err
}
// Set the stream urls on all of the tracks:
for index, track := range searchTracksResponse.Data {
streamURL := *selectedHostURL
streamURL.Path = "/v1/tracks/" + track.ID + "/stream"
track.StreamURL = streamURL.String()
searchTracksResponse.Data[index] = track
}
return searchTracksResponse, nil
}