go-freeGeoIP client with inbuilt cache
![Coverage Status](https://coveralls.io/repos/github/Shivam010/go-freeGeoIP/badge.svg)
go-freeGeoIP is a Golang client for Free IP Geolocation information API with inbuilt cache support to
increase the 15k per hour rate limit of the application https://freegeoip.app/
By default, the client will cache the IP Geolocation information for 24 hours, but the expiry can be set manually.
If you want set the information cache with no expiration time set the expiry function to nil.
A 24-hour cache expiry will be sufficient overcome the 15k per hour limit.
Installation
go get github.com/Shivam010/go-freeGeoIP
FreeGeoIP.app description
freegeoip.app provides a free IP geolocation API for software developers. It uses a database of IP addresses that
are associated to cities along with other relevant information like time zone, latitude and longitude.
You're allowed up to 15,000 queries per hour by default. Once this limit is reached, all of your requests will
result in HTTP 403, forbidden, until your quota is cleared.
The HTTP API takes GET requests in the following schema:
https://freegeoip.app/{format}/{IP_or_hostname}
Supported formats are: csv, xml, json and jsonp. If no IP or hostname is provided, then your own IP is looked up.
Usage
package main
import (
"context"
"github.com/Shivam010/go-freeGeoIP"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
func main() {
ctx := context.Background()
cli := freeGeoIP.DefaultClient()
res := cli.GetGeoInfoFromString(ctx, "8.8.8.8")
if err := res.Error; err != nil {
log.Println(err)
return
}
cli.Logger.Println(res.Cached)
res = cli.GetGeoInfoFromString(ctx, "8.8.8.8")
if err := res.Error; err != nil {
log.Println(err)
return
}
cli.Logger.Println(res.Cached)
cli = &freeGeoIP.Client{}
res = cli.GetGeoInfo(ctx, freeGeoIP.IP{8, 8, 8, 8})
if err := res.Error; err != nil {
log.Println(err)
return
}
cache := freeGeoIP.NewCache(freeGeoIP.NoCacheExpiration,
func(ctx context.Context, ip freeGeoIP.IP) time.Duration {
if value := ctx.Value("IP_Skip_Pattern"); value != nil {
if pat, ok := value.(string); ok {
if strings.Contains(ip.String(), pat) {
return freeGeoIP.SkipCache
}
}
}
return freeGeoIP.NoCacheExpiration
},
)
cache = freeGeoIP.NewCache(freeGeoIP.NoCacheExpiration, nil)
cli = &freeGeoIP.Client{
Cache: cache,
HttpCli: &http.Client{Timeout: time.Second},
Logger: log.New(ioutil.Discard, "", 0),
}
res = cli.GetGeoInfo(ctx, freeGeoIP.IP{8, 8, 8, 8})
if err := res.Error; err != nil {
log.Println(err)
return
}
}
Request for Contribution
Contributors are more than welcome and much appreciated. Please feel free to open a PR to improve anything you
don't like, or would like to add.
Please make your changes in a specific branch and create a pull request into master! If you can, please make sure all
the changes work properly and does not affect the existing functioning.
No PR is too small! Even the smallest effort is countable.
License
This project is licensed under the Apache License 2.0