-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
45 lines (37 loc) · 1.06 KB
/
http.go
File metadata and controls
45 lines (37 loc) · 1.06 KB
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
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
func getGameData(gameID int) (map[string]interface{}, error) {
resp, respErr := http.Get(fmt.Sprintf("https://statsapi.mlb.com/api/v1.1/game/%d/feed/live", gameID))
if respErr != nil {
return nil, respErr
}
defer resp.Body.Close()
body, ioErr := io.ReadAll(resp.Body)
if ioErr != nil {
return nil, ioErr
}
var mlbDataJSON map[string]interface{}
if unmarshalErr := json.Unmarshal(body, &mlbDataJSON); unmarshalErr != nil {
return nil, unmarshalErr
}
return mlbDataJSON, nil
}
func getGameStats(gameData map[string]interface{}) (map[string]interface{}, error) {
return unwrap(gameData, "gameData")
}
func getLiveStats(gameData map[string]interface{}) (map[string]interface{}, error) {
return unwrap(gameData, "liveData")
}
func unwrap(jsonData map[string]interface{}, key string) (map[string]interface{}, error) {
nestedData, ok := jsonData[key].(map[string]interface{})
if !ok {
return nil, errors.New(fmt.Sprintf("Key %s not found in JSON data", key))
}
return nestedData, nil
}