mlblive/internal/statsapi/client.go

85 lines
1.9 KiB
Go
Raw Normal View History

2024-07-02 04:16:44 +00:00
package statsapi
import (
2024-07-13 20:09:10 +00:00
"io"
2024-07-02 04:16:44 +00:00
"net/http"
"net/url"
)
var DefaultClient = NewClient(http.DefaultClient)
2024-07-13 20:35:43 +00:00
func RequestSchedule(sportId, teamId string) ([]byte, error) {
return DefaultClient.RequestSchedule(sportId, teamId)
2024-07-02 04:16:44 +00:00
}
2024-07-13 20:35:43 +00:00
func RequestFeed(gamePk string) ([]byte, error) {
return DefaultClient.RequestFeed(gamePk)
2024-07-02 04:16:44 +00:00
}
2024-07-13 20:35:43 +00:00
func RequestDiffPatch(gamePk, startTimecode, pushUpdateId string) ([]byte, error) {
return DefaultClient.RequestDiffPatch(gamePk, startTimecode, pushUpdateId)
2024-07-02 04:16:44 +00:00
}
type Client struct {
baseURL url.URL
httpClient *http.Client
}
func NewClient(c *http.Client) *Client {
return &Client{
baseURL: url.URL{
Scheme: "https",
Host: "statsapi.mlb.com",
},
httpClient: c,
}
}
2024-07-13 20:35:43 +00:00
func (c *Client) RequestSchedule(sportId, teamId string) ([]byte, error) {
2024-07-02 04:16:44 +00:00
endpoint := url.URL{Path: "api/v1/schedule"}
query := endpoint.Query()
query.Add("sportId", sportId)
query.Add("teamId", teamId)
endpoint.RawQuery = query.Encode()
url := c.baseURL.ResolveReference(&endpoint)
2024-07-13 20:09:10 +00:00
return c.get(url.String())
2024-07-02 04:16:44 +00:00
}
2024-07-13 20:35:43 +00:00
func (c *Client) RequestFeed(gamePk string) ([]byte, error) {
2024-07-02 04:16:44 +00:00
endpoint := url.URL{Path: "api/v1.1/game/" + gamePk + "/feed/live"}
url := c.baseURL.ResolveReference(&endpoint)
2024-07-13 20:09:10 +00:00
return c.get(url.String())
2024-07-02 04:16:44 +00:00
}
2024-07-13 20:35:43 +00:00
func (c *Client) RequestDiffPatch(gamePk, startTimecode, pushUpdateId string) ([]byte, error) {
2024-07-02 04:16:44 +00:00
endpoint := url.URL{Path: "api/v1.1/game/" + gamePk + "/feed/live/diffPatch"}
query := endpoint.Query()
query.Add("language", "en")
query.Add("startTimecode", startTimecode)
query.Add("pushUpdateId", pushUpdateId)
endpoint.RawQuery = query.Encode()
url := c.baseURL.ResolveReference(&endpoint)
2024-07-13 20:09:10 +00:00
return c.get(url.String())
2024-07-02 04:16:44 +00:00
}
2024-07-13 20:09:10 +00:00
func (c *Client) get(url string) ([]byte, error) {
2024-07-02 04:16:44 +00:00
req, err := http.NewRequest("GET", url, nil)
if err != nil {
2024-07-13 20:09:10 +00:00
return nil, err
2024-07-02 04:16:44 +00:00
}
resp, err := c.httpClient.Do(req)
if err != nil {
2024-07-13 20:09:10 +00:00
return nil, err
2024-07-02 04:16:44 +00:00
}
defer resp.Body.Close()
2024-07-13 20:09:10 +00:00
body, err := io.ReadAll(resp.Body)
return body, err
2024-07-02 04:16:44 +00:00
}