Skip to content

Instantly share code, notes, and snippets.

@devig
Created August 26, 2019 11:53
Show Gist options
  • Save devig/cd976c7827bcc7203995a348a69827e7 to your computer and use it in GitHub Desktop.
Save devig/cd976c7827bcc7203995a348a69827e7 to your computer and use it in GitHub Desktop.
Filter countries
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
)
type Page struct {
Data []Country `json:"data,omitempty"`
TotalPages int `json:"total_pages,omitempty"`
}
type Country struct {
Population int `json:"population,omitempty"`
}
func ExtractFromJSON (url string) *Page {
resp, err := http.Get(url)
if err != nil {
log.Fatalln(err)
}
decoder := json.NewDecoder(resp.Body)
val := &Page{}
err = decoder.Decode(val)
if err != nil {
log.Fatal(err)
}
return val
}
func getCountries(s string,p int) int {
startURL := "https://jsonmock.hackerrank.com/api/countries/search?name="+s+"&page="
val := ExtractFromJSON(startURL+"1")
sum := 0
for i := 1; i <= val.TotalPages; i++ {
val := ExtractFromJSON(startURL+strconv.Itoa(i))
for _, s := range val.Data {
if s.Population>p {
sum++
}
}
}
return sum
}
func main() {
fmt.Println(getCountries("b", 1000000))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment