-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdata.go
66 lines (56 loc) · 1.17 KB
/
data.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
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
)
var (
httpClient = http.Client{}
baseURL = "https://interaktiv.morgenpost.de"
currentDataEndpoint = "/data/corona/current.v4.csv"
historicalDataEndpoint = "/data/corona/history.light.v4.csv"
currentDataURL = fmt.Sprintf("%s%s", baseURL, currentDataEndpoint)
historicalDataURL = fmt.Sprintf("%s%s", baseURL, historicalDataEndpoint)
)
func saveData(ctx context.Context, url, file string) error {
errChan := make(chan error)
go func() {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
errChan <- err
return
}
req.Header.Add("user-agent", "Mozilla/5.0")
res, err := httpClient.Do(req)
if err != nil {
errChan <- err
return
}
defer res.Body.Close()
f, err := os.Create(file)
if err != nil {
errChan <- err
return
}
defer f.Close()
_, err = io.Copy(f, res.Body)
if err != nil {
errChan <- err
return
}
errChan <- nil
}()
for {
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errChan:
if err != nil {
return fmt.Errorf("saveData: %w", err)
}
return nil
}
}
}