-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsleeper.go
103 lines (81 loc) · 2.14 KB
/
sleeper.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package sleeper
import (
"encoding/json"
"fmt"
"net/http"
)
// Client is a client for working with the sleeper.app read only Web API
type Client struct {
httpClient *http.Client
sleeperURL string
sleeperCDN string
NFLPlayers AllPlayers
}
// NewClient creates a new Sleeper Client.
func NewClient(httpClient *http.Client) (*Client, error) {
c := &Client{
httpClient: httpClient,
sleeperURL: SLEEPER_BASE_URL,
sleeperCDN: SLEEPER_BASE_CDN,
}
return c, nil
}
// Error represents an error returned by the sleeper.app Web API.
type Error struct {
// A short description of the error.
Message string `json:"message"`
// The HTTP status code.
Err int `json:"error"`
}
// Error ...
func (e Error) Error() string {
return e.Message
}
// decodeError decodes an Error from response status code based off
// the docs in sleeper.app -> https://docs.sleeper.app/#errors
func (c *Client) decodeError(statusCode int) error {
e := Error{Err: statusCode}
switch e.Err {
case 400:
e.Message = "Bad Request -- Your request is invalid."
case 404:
e.Message = "Not Found -- The specified kitten could not be found."
case 429:
e.Message = "Too Many Requests -- You're requesting too many kittens! Slow down!"
case 500:
e.Message = "Internal Server Error -- We had a problem with our server. Try again later."
case 503:
e.Message = "Service Unavailable -- We're temporarily offline for maintenance. Please try again later."
default:
e.Message = fmt.Sprintf("lastfm: unexpected HTTP %d: %s (empty error)",
statusCode, http.StatusText(statusCode))
}
return e
}
// get handles the get requests for the client
func (c *Client) get(url string, result any) error {
for {
resp, err := c.httpClient.Get(url)
if err != nil {
return err
}
// body, err := ioutil.ReadAll(resp.Body)
// if err != nil {
// return err
// }
// fmt.Println(string(body))
defer resp.Body.Close()
if resp.StatusCode == http.StatusNoContent {
return nil
}
if resp.StatusCode != http.StatusOK {
return c.decodeError(resp.StatusCode)
}
err = json.NewDecoder(resp.Body).Decode(result)
if err != nil {
return err
}
break
}
return nil
}