Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created February 9, 2018 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/84a06c162b9024125cc55b05f9f6de8f to your computer and use it in GitHub Desktop.
Save xeoncross/84a06c162b9024125cc55b05f9f6de8f to your computer and use it in GitHub Desktop.
Example of using https://github.com/fiorix/freegeoip geoip database in golang

Usage

You can specify a file location, or just let it download one for you.

A) Local database:

wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz

Then just load it

// Load IP database
err = IPDB.Load("db.gz")
if err != nil {
	logger.Fatal(err)
}
defer IPDB.Close()

B) Auto-updating remote database: link

// Load IP database
err = IPDB.Load("")
if err != nil {
	logger.Fatal(err)
}
defer IPDB.Close()

Usage

var s freegeoip.DefaultQuery
theStruct, err := IPDB.Lookup("8.8.8.8")
if err != nil {
	log.Println(err)
	continue
}
fmt.Println(theStruct)
package main
import (
"net"
"time"
"github.com/fiorix/freegeoip"
)
// IPDatabase Wrapper Struct
type IPDatabase struct {
DB *freegeoip.DB
}
// Load the Database
func (i *IPDatabase) Load(location string) (err error) {
if len(location) != 0 {
i.DB, err = freegeoip.Open(location)
if err != nil {
return
}
} else {
updateInterval := 24 * time.Hour
maxRetryInterval := time.Hour
i.DB, err = freegeoip.OpenURL(freegeoip.MaxMindDB, updateInterval, maxRetryInterval)
if err != nil {
return
}
}
select {
case <-i.DB.NotifyOpen():
// Wait for the db to be downloaded.
case err = <-i.DB.NotifyError():
return
}
return
}
// Close the database connection
func (i *IPDatabase) Close() {
i.DB.Close()
}
// Lookup an IP in the database
func (i *IPDatabase) Lookup(ipAddress string) (result freegeoip.DefaultQuery, err error) {
err = i.DB.Lookup(net.ParseIP(ipAddress), &result)
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment