a Medically trained Computer Scientist

Geolocation

Since we obtain client’s external IP address, we can add more useful feature such as geolocation to pinpoint the address of internet connection the laptop is connected on. In this program, we use a freely available api from freegeoip.net. It can give a rough estimate of our ‘missing’ laptop location. It can’t pinpoint to the exact address, you’d need a more comprehensive IP database (which will cost you money).

This is also a good way to introduce JSON with Go and how simple to use it. These codes are adapted from devdungeon.com

We start with a struct.

typeGeoIPstruct{// The right side is the name of the JSON variableIpstring`json:"ip"`CountryCodestring`json:"country_code"`CountryNamestring`json:"country_name"`RegionCodestring`json:"region_code"`RegionNamestring`json:"region_name"`Citystring`json:"city"`Zipcodestring`json:"zipcode"`Latfloat32`json:"latitude"`Lonfloat32`json:"longitude"`MetroCodeint`json:"metro_code"`AreaCodeint`json:"area_code"`}

We define a struct type called GeoIP. The leftmost variable is the name of the field we are going to use in our upcoming GeoLookup function. Next, variable type. Lastly, the json data determined by the api provider.

funcGeoLookup(addressstring)GeoIP{// Use freegeoip.net to get a JSON response// There is also /xml/ and /csv/ formats availableresponse,err=http.Get("https://freegeoip.net/json/"+address)iferr!=nil{fmt.Println(err)}deferresponse.Body.Close()// response.Body() is a reader type. We have// to use ioutil.ReadAll() to read the data// in to a byte slice(string)body,err=ioutil.ReadAll(response.Body)iferr!=nil{fmt.Println(err)}// Unmarshal the JSON byte slice to a GeoIP structerr=json.Unmarshal(body,&geo)iferr!=nil{fmt.Println(err)}returngeo}

From runClient() function, we are going to call this GeoLookup() function by passing the client’s external IP address. The byte slice body, which is in json format, is ‘unwrapped’, matched with our GeoIP struct and referenced by geo variable (which is our return type). A simple one line err = json.Unmarshal(body, &geo) is what needed to make this happen.

Next, we need to update runClient() function to send this data to server.