-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
78 lines (70 loc) · 1.99 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
package nag
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"net/http"
"net/url"
)
var (
// DefaultBaseURL sets default base URL for request to NBA stats.
DefaultBaseURL = &url.URL{
Host: "stats.nba.com",
Scheme: "https",
Path: "/stats",
}
// DefaultStatsHeader sets default headers for request to NBA stats.
// no idea which is necessary and which is not
DefaultStatsHeader = http.Header{
"Host": []string{"stats.nba.com"},
"Referer": []string{"https://stats.nba.com"},
"User-Agent": []string{"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0"},
"Connection": []string{"keep-alive"},
"Pragma": []string{"no-cache"},
"Cache-Control": []string{"no-cache"},
"Accept": []string{"application/json", "text/plain", "*/*"},
"Accept-Encoding": []string{"gzip", "deflate", "br"},
"Accept-Language": []string{"en-US,en;q=0.9"},
"x-nba-stats-origin": []string{"stats"},
"x-nba-stats-token": []string{"true"},
}
)
// Client contains the base URL to send request to and the HTTP client being used.
type Client struct {
BaseURL *url.URL
HTTPClient *http.Client
}
// NewDefaultClient uses stdlib default HTTP client to make request to
// default NBA stats endpoint.
func NewDefaultClient() *Client {
return &Client{
BaseURL: DefaultBaseURL,
HTTPClient: http.DefaultClient,
}
}
// Do sends request to NBA stats endpoint and unpacks the received response.
func (c *Client) Do(req *http.Request) ([]byte, error) {
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s status code: %d", req.URL.String(), res.StatusCode)
}
defer res.Body.Close()
b, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
gr, err := gzip.NewReader(bytes.NewReader(b))
if err != nil {
return nil, nil
}
defer gr.Close()
b, err = io.ReadAll(gr)
if err != nil {
return nil, err
}
return b, nil
}