-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
101 lines (86 loc) · 2.22 KB
/
client.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
package espn
import (
"encoding/json"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
"time"
)
type espnClient struct {
HTTPClient *http.Client
espnURL string
basePath string
baseLeaguePath string
}
func newPublicClient(gameType GameType, leagueID string, year int) *espnClient {
basePath := fmt.Sprintf("/%s/seasons/%d", gameType, year)
var baseLeaguePath string
if year < 2018 {
baseLeaguePath = fmt.Sprintf("/%s/leagueHistory/%s?seasonId=%d", gameType, leagueID, year)
} else {
baseLeaguePath = fmt.Sprintf("%s/segments/0/leagues/%s", basePath, leagueID)
}
return &espnClient{
espnURL: espnBaseURL,
basePath: basePath,
baseLeaguePath: baseLeaguePath,
HTTPClient: &http.Client{
Timeout: time.Minute,
},
}
}
func newPrivateClient(gameType GameType, leagueID string, year int, espnS2 string, swid string) *espnClient {
jar, _ := cookiejar.New(nil)
url, _ := url.Parse(espnBaseURL)
cookies := make([]*http.Cookie, 2)
cookies[0] = &http.Cookie{
Name: "espn_s2",
Value: espnS2,
}
cookies[1] = &http.Cookie{
Name: "SWID",
Value: swid,
}
jar.SetCookies(url, cookies)
client := newPublicClient(gameType, leagueID, year)
client.HTTPClient.Jar = jar
return client
}
func (c *espnClient) sendRequest(req *http.Request, v interface{}) error {
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
return fmt.Errorf("unknown error, status code: %d", res.StatusCode)
}
if err = json.NewDecoder(res.Body).Decode(&v); err != nil {
return err
}
return nil
}
func (c *espnClient) getLeagueInternal(views []string, filter string, extend string, v interface{}) error {
req, err := http.NewRequest("GET", fmt.Sprintf("%s%s%s", c.espnURL, c.baseLeaguePath, extend), nil)
if err != nil {
fmt.Printf("error in espn request: %v", err)
return err
}
if filter != "" {
req.Header.Add("x-fantasy-filter", filter)
}
if len(views) > 0 {
q := req.URL.Query()
for _, v := range views {
q.Add("view", v)
}
req.URL.RawQuery = q.Encode()
}
err = c.sendRequest(req, &v)
if err != nil {
fmt.Printf("error in espn request: %v", err)
return err
}
return nil
}