Last active
November 13, 2018 15:38
-
-
Save jreisinger/0c09ababe78e49707fc897a9c2ba9ed6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "github.com/oschwald/geoip2-golang" | |
| "log" | |
| "net" | |
| "os" | |
| ) | |
| // geolocate returns the geographical location of the IP address. | |
| func geolocate(ipaddr string) (string, error) { | |
| // Download from https://dev.maxmind.com/geoip/geoip2/geolite2/ | |
| MaxMindDB := "GeoLite2-City.mmdb" | |
| db, err := geoip2.Open(MaxMindDB) | |
| if err != nil { | |
| return "", err | |
| } | |
| defer db.Close() | |
| ip := net.ParseIP(ipaddr) | |
| record, err := db.City(ip) | |
| if err != nil { | |
| return "", err | |
| } | |
| return record.Country.Names["en"], nil | |
| } | |
| func main() { | |
| if len(os.Args) != 2 { | |
| fmt.Fprintf(os.Stderr, "You need to supply an IP address\n") | |
| os.Exit(1) | |
| } | |
| ipaddr := os.Args[1] | |
| loc, err := geolocate(ipaddr) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| fmt.Println(loc) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment