Skip to content

Instantly share code, notes, and snippets.

@crissilvaeng
Last active May 26, 2020 15:04
Show Gist options
  • Save crissilvaeng/1cf252645dba420e4bcf7d34a07710d5 to your computer and use it in GitHub Desktop.
Save crissilvaeng/1cf252645dba420e4bcf7d34a07710d5 to your computer and use it in GitHub Desktop.
COVID-19 stats CLI
// Copyright (c) 2020 Cristina Silva (crissilvaeng) <[email protected]>
// License: X11 License (X11) <https://spdx.org/licenses/X11.html>
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
type stats struct {
Country string `json:"Country"`
Confirmed int `json:"Confirmed"`
Deaths int `json:"Deaths"`
Recovered int `json:"Recovered"`
Active int `json:"Active"`
Date time.Time `json:"Date"`
}
const (
baseURL = "https://api.covid19api.com/country/%s"
layout = "Mon Jan _2 2006"
)
var country string
var printer *message.Printer
var increase = []string{"(\033[1;31m+\033[0m)", "(\033[1;33m~\033[0m)", "(\033[1;32m-\033[0m)"}
var decrease = []string{"(\033[1;32m+\033[0m)", "(\033[1;33m~\033[0m)", "(\033[1;31m-\033[0m)"}
func init() {
flag.StringVar(&country, "country", "brazil", "selected country to show covid stats")
flag.Parse()
printer = message.NewPrinter(language.BrazilianPortuguese)
}
func main() {
stats, err := retrieveStats(country)
if err != nil {
log.Fatal(err)
}
last := stats[len(stats)-1]
before := last
if len(stats) >= 2 {
before = stats[len(stats)-2]
}
fmt.Printf("🦠 COVID-19 at %s until %s\n\n", last.Country, last.Date.Format(layout))
fmt.Printf("🀧 Confirmed: %s\n", compareStats(last.Confirmed, before.Confirmed, increase))
fmt.Printf("😷 Active: %s\n", compareStats(last.Active, before.Active, increase))
fmt.Printf("πŸ€• Recovered: %s\n", compareStats(last.Recovered, before.Recovered, decrease))
fmt.Printf("πŸ’€ Deaths: %s\n\n", compareStats(last.Deaths, before.Deaths, increase))
fmt.Println("πŸ”¬ Source: https://api.covid19api.com")
}
func retrieveStats(country string) ([]stats, error) {
url := fmt.Sprintf(baseURL, country)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
stats := []stats{}
err = json.Unmarshal(body, &stats)
if err != nil {
return nil, err
}
return stats, nil
}
func compareStats(last int, before int, palette []string) string {
switch {
case last > before:
return printer.Sprintf("%d %s", last, palette[0])
case last == before:
return printer.Sprintf("%d %s", last, palette[1])
default:
return printer.Sprintf("%d %s", last, palette[2])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment