/
avatar.go
84 lines (70 loc) · 1.63 KB
/
avatar.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 oauth
import (
"fmt"
"net/http"
)
// AvatarURL returns the URL of the user associated with userID.
// Non-positive sizes are ignored, positive sizes are validated according to
// the values at https://developer.wunderlist.com/documentation/endpoints/avatar.
func (c oauthClient) AvatarURL(userID uint, size int, fallback bool) (string, error) {
url := fmt.Sprintf(
"%s/avatar?user_id=%d",
c.apiURL,
userID,
)
if size > 0 {
if !c.validSize(size) {
return "", fmt.Errorf("Invalid size: %d", size)
}
url = fmt.Sprintf(
"%s&size=%d",
url,
size,
)
}
if !fallback {
url = fmt.Sprintf(
"%s&fallback=%t",
url,
fallback,
)
}
req, err := c.newGetRequest(url)
if err != nil {
return "", err
}
c.logRequest(req)
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
return "", err
}
if resp != nil {
c.logResponse(resp)
}
if fallback {
if resp.StatusCode != http.StatusFound {
return "", fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusFound)
}
} else {
if resp.StatusCode == http.StatusNoContent {
return "", nil
}
if resp.StatusCode != http.StatusFound {
return "", fmt.Errorf("Unexpected response code %d - expected either %d or %d", resp.StatusCode, http.StatusNoContent, http.StatusFound)
}
}
location, err := resp.Location()
if err != nil {
return "", err
}
return location.String(), nil
}
func (c oauthClient) validSize(size int) bool {
validSizes := []int{25, 28, 30, 32, 50, 54, 56, 60, 64, 108, 128, 135, 256, 270, 512}
for _, s := range validSizes {
if s == size {
return true
}
}
return false
}