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
/
get_resolved_resource.go
79 lines (69 loc) · 1.62 KB
/
get_resolved_resource.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
package audiusclient
import (
"errors"
"io/ioutil"
"net/http"
"strings"
)
// GetResolvedResource -
func (c *Client) GetResolvedResource(audiusURL string) (resourceType string, resourceID string, err error) {
// Select an audius host:
selectedHostURL, err := c.GetHost()
if err != nil {
return
}
requestURL := *selectedHostURL
requestURL.Path = "/v1/resolve"
// Build the query:
values := requestURL.Query()
values.Set("url", audiusURL)
requestURL.RawQuery = values.Encode()
// Create a client that won't redirect:
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
// Fetch the hosts:
urlString := requestURL.String()
res, err := client.Get(urlString)
if err != nil {
return
}
defer res.Body.Close()
if res.StatusCode != 302 {
// Parse the error:
var body []byte
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return
}
err = errors.New(string(body))
return
}
// Get the redirected url:
redirectedURL, err := res.Location()
if err != nil {
return
}
// Parse the redirected URL into the resource type and ID:
resourcePath := strings.TrimPrefix(redirectedURL.Path, "/v1/")
resourcePathComponents := strings.Split(resourcePath, "/")
if len(resourcePathComponents) != 2 {
err = errors.New("invalid resource path")
return
}
resourceID = resourcePathComponents[1]
switch resourcePathComponents[0] {
case "playlists":
resourceType = "playlist"
case "tracks":
resourceType = "track"
case "users":
resourceType = "user"
default:
err = errors.New("invalid resource path")
return
}
return
}