github.com/wtfutil/wtf@v0.43.0/modules/covid/client.go (about) 1 package covid 2 3 import ( 4 "fmt" 5 "net/http" 6 7 "github.com/wtfutil/wtf/utils" 8 ) 9 10 const covidTrackerAPIURL = "https://coronavirus-tracker-api.herokuapp.com/v2/" 11 12 // LatestCases queries the /latest endpoint, does not take any query parameters 13 func LatestCases() (*Cases, error) { 14 latestURL := covidTrackerAPIURL + "latest" 15 resp, err := http.Get(latestURL) 16 if resp.StatusCode != 200 { 17 return nil, fmt.Errorf(resp.Status) 18 } 19 if err != nil { 20 return nil, err 21 } 22 defer func() { _ = resp.Body.Close() }() 23 24 var latestGlobalCases Cases 25 err = utils.ParseJSON(&latestGlobalCases, resp.Body) 26 if err != nil { 27 return nil, err 28 } 29 30 return &latestGlobalCases, nil 31 } 32 33 // LatestCountryCases queries the /locations endpoint, takes a query parameter: the country code 34 func (widget *Widget) LatestCountryCases(countries []interface{}) ([]*Cases, error) { 35 countriesCovidData := []*Cases{} 36 for _, name := range countries { 37 countryURL := covidTrackerAPIURL + "locations?source=jhu&country_code=" + name.(string) 38 resp, err := http.Get(countryURL) 39 if resp.StatusCode != 200 { 40 return nil, fmt.Errorf(resp.Status) 41 } 42 if err != nil { 43 return nil, err 44 } 45 defer func() { _ = resp.Body.Close() }() 46 47 var latestCountryCases Cases 48 err = utils.ParseJSON(&latestCountryCases, resp.Body) 49 if err != nil { 50 return nil, err 51 } 52 // add stats for each country to the slice 53 countriesCovidData = append(countriesCovidData, &latestCountryCases) 54 55 } 56 57 return countriesCovidData, nil 58 }