-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.go
100 lines (77 loc) · 1.71 KB
/
api.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
package mlb
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// schedule?lang=en&sportId=1&season=2018&startDate=2018-08-01&endDate=2018-08-31&teamId=119&eventTypes=primary&scheduleTypes=games
func (m *Mlb) Call(endpoint string, query map[string]string) (Response, error) {
if query == nil {
query = make(map[string]string)
}
result := Response{}
timeout := time.Duration(10 * time.Second)
client := http.Client{
Timeout: timeout,
}
if len(endpoint) < 2 {
return result, errors.New("Invalid endpoint")
}
if string(endpoint[0]) == "/" {
endpoint = endpoint[1:]
}
u := fmt.Sprintf("%s/%s",
baseApiURL,
endpoint,
)
if query["lang"] == "" {
query["lang"] = "en"
}
for k, v := range query {
m.log(" - ", k, v)
if !strings.Contains(u, "?") {
u = u + "?" + k + "=" + url.QueryEscape(v)
continue
}
u = u + "&" + k + "=" + url.QueryEscape(v)
}
_url, err := url.Parse(u)
if err != nil {
ifError(err)
return result, err
}
m.log("calling:", _url.String())
resp, err := client.Get(_url.String())
if err != nil {
return result, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
ifError(err)
return result, err
}
if body != nil {
err = json.Unmarshal([]byte(body), &result)
if err != nil {
ifError(err)
return result, err
}
}
// m.log(" - body: \n %s", string(body))
m.log("status code:", resp.StatusCode)
switch resp.StatusCode {
case 200:
return result, nil
case 404:
return result, errors.New("Error (Not Found): " + result.Message)
default:
return result, errors.New("Invalid response code from MLB.com, StatusCode: " + strconv.Itoa(resp.StatusCode))
}
}