I want to count geolocations of IP addresses by country and then by city. The expected output would be something like:
$ cat ips.txt | ./geoips
United States 42
Washington 21
New York 21
China 10
Beijing 10
I came up with this code that uses map of maps to keep the counts:
func main() {
ips := parseIPs(getIPs())
counts := make(map[string]map[string]int)
for _, ip := range ips {
g := &checkip.Geo{}
_, err := g.Check(ip)
if err != nil {
log.Printf("while getting geolocation: %v", err)
continue
}
counts[g.Country][g.City]++
}
fmt.Printf("%v\n", counts)
}
When I build and run it a get an error:
$ cat ips.txt | ./geoips
panic: assignment to entry in nil map
goroutine 1 [running]:
main.main()
/Users/xxx/geoips/main.go:30 +0x245
I understand the problem is that the 2nd map is not initialised. How do I do that?
Or is there a better way to keep the counts?