-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetcher.go
108 lines (88 loc) · 2.29 KB
/
fetcher.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
102
103
104
105
106
107
108
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
/*
Games Collection
https://api.volleyball.ch/indoor/games
Club Rankings
https://api.volleyball.ch/indoor/ranking
Upcoming Games Collection
https://api.volleyball.ch/indoor/upcomingGames
Recent Results Collection
https://api.volleyball.ch/indoor/recentResults
*/
const gamesCollectionUri = "https://api.volleyball.ch/indoor/games"
const clubRankingsUri = "https://api.volleyball.ch/indoor/ranking"
type fetcher struct {
apiKey string
state *state
// Make the request
httpClient *http.Client
}
func newFetcher(apiKey string, state *state) (*fetcher, error) {
internalFetcher := fetcher{
apiKey: apiKey,
state: state,
httpClient: &http.Client{},
}
return &internalFetcher, nil
}
func (f fetcher) fetch() error {
// Fetch rawGames collection
req, err := http.NewRequest("GET", gamesCollectionUri, nil)
if err != nil {
fmt.Printf("Error creating request: %v\n", err)
return err
}
req.Header.Set("Authorization", f.apiKey)
resp, err := f.httpClient.Do(req)
if err != nil {
fmt.Printf("Error making request: %v\n", err)
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error reading response body: %v\n", err)
return err
}
fmt.Printf("used apiKey: %v\n", f.apiKey)
var games []Game
if err := json.Unmarshal(body, &games); err != nil {
fmt.Printf("Body: %v\n", bytes.NewBuffer(body).String())
fmt.Printf("Error unmarshalling games response: %v\n", err)
return err
}
// Fetch the rawRankings
req, err = http.NewRequest("GET", clubRankingsUri, nil)
if err != nil {
fmt.Printf("Error creating request: %v\n", err)
return err
}
req.Header.Set("Authorization", f.apiKey)
resp, err = f.httpClient.Do(req)
if err != nil {
fmt.Printf("Error making request: %v\n", err)
return err
}
defer resp.Body.Close()
body, err = io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error reading response body: %v\n", err)
return err
}
var rankings []GroupRankings
if err := json.Unmarshal(body, &rankings); err != nil {
fmt.Printf("Body: %v\n", bytes.NewBuffer(body).String())
fmt.Printf("Error unmarshalling rankings response: %v\n", err)
return err
}
f.state.rawGames = games
f.state.rawRankings = rankings
return nil
}