-
Notifications
You must be signed in to change notification settings - Fork 0
/
covidcli.go
129 lines (110 loc) · 2.64 KB
/
covidcli.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/ipeluffo/covidcli/models"
"github.com/urfave/cli/v2"
)
const (
flagFrom = "from"
flagTo = "to"
flagCountry = "country"
dateFormat = "2006-01-02"
)
func commandAction(ctx *cli.Context) error {
var from *time.Time = ctx.Timestamp(flagFrom)
var to *time.Time = ctx.Timestamp(flagTo)
var country string = ctx.String(flagCountry)
// I'd like to use https://documenter.getpostman.com/view/10808728/SzS8rjbc?version=latest#9739c95f-ef1d-489b-97a9-0a6dfe2f74d8
// but dates filters don't work
apiURL := "https://api.covid19api.com/country/%s?from=%s&to=%s"
url := fmt.Sprintf(apiURL, country, from.Format(dateFormat), to.Format(dateFormat))
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var records []models.Stats
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
json.Unmarshal(body, &records)
// Alternative
// json.NewDecoder(resp.Body).Decode(&records)
var lastDeaths int = 0
var lastDeathsDiff int = 0
for _, stats := range records {
// Skip cities stats.
// This is a workaround since we cannot use totals per country endpoint.
if stats.Province != "" {
continue
}
diff := stats.Deaths - lastDeaths
var diffEmoji string
var deathsEmoji string
if diff == 0 {
deathsEmoji = "🎉"
} else {
deathsEmoji = "💀"
}
if diff > lastDeathsDiff {
diffEmoji = "📈"
} else if diff < lastDeathsDiff {
diffEmoji = "📉"
}
// This stat usually comes as zero, if this is case then calculate it
var active int = stats.Active
if active == 0 {
active = stats.Confirmed - stats.Deaths - stats.Recovered
}
fmt.Println(stats.Date)
fmt.Println("Confirmed:", stats.Confirmed)
fmt.Println("Deaths:", stats.Deaths, deathsEmoji, "Diff:", diff, diffEmoji)
fmt.Println("Recovered:", stats.Recovered)
fmt.Println("Active:", active)
fmt.Println()
lastDeaths = stats.Deaths
lastDeathsDiff = diff
}
return nil
}
func main() {
app := &cli.App{
Authors: []*cli.Author{
&cli.Author{
Name: "Ignacio Peluffo",
Email: "[email protected]",
},
},
Version: "2020.04.19",
Name: "covidcli",
Usage: "Get COVID-19 stats on your terminal",
Action: commandAction,
Flags: []cli.Flag{
&cli.TimestampFlag{
Name: flagFrom,
Required: true,
Layout: "2006-01-02",
},
&cli.TimestampFlag{
Name: flagTo,
Required: true,
Layout: "2006-01-02",
},
&cli.StringFlag{
Name: flagCountry,
Required: true,
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}