Skip to content

Instantly share code, notes, and snippets.

@sosedoff
Created March 11, 2015 12:12
Show Gist options
  • Save sosedoff/09b106f11023eec82c98 to your computer and use it in GitHub Desktop.
Save sosedoff/09b106f11023eec82c98 to your computer and use it in GitHub Desktop.
geoip2 golang test
package main
import (
"log"
"net"
"os"
"github.com/gin-gonic/gin"
"github.com/sosedoff/geoip2-golang"
)
var database *geoip2.Reader
func jsonError(message string, c *gin.Context) {
c.JSON(400, map[string]string{"error": message})
}
func GetIpInfo(c *gin.Context) {
ip := net.ParseIP(c.Params.ByName("ip"))
if ip == nil {
jsonError("Invalid IPv4 address", c)
return
}
record, err := database.City(ip)
if err != nil {
jsonError(err.Error(), c)
return
}
c.JSON(200, record)
}
func main() {
dbpath := os.Getenv("GEOLITE2_DB")
if dbpath == "" {
log.Fatal("GEOLITE2_DB is not provided")
}
db, err := geoip2.Open(dbpath)
if err != nil {
log.Fatal(err)
}
database = db
defer db.Close()
router := gin.Default()
router.GET("/ip/:ip", GetIpInfo)
router.Run(":5000")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment