freeGeoIP

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 24, 2020 License: Apache-2.0 Imports: 14 Imported by: 1

README

go-freeGeoIP client with inbuilt cache

Build Go Report Card GoDoc License GitHub release Coverage Status

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()

	// Using default client which comes with an in-memory cache implementation
	// with 24 Hour expiry and a http.Client timeout of 2 seconds and a default
	// `log.Logger`
	cli := freeGeoIP.DefaultClient()
	res := cli.GetGeoInfoFromString(ctx, "8.8.8.8")
	if err := res.Error; err != nil {
		log.Println(err)
		return
	}
	// first time retrieval and hence, not a cached output
	cli.Logger.Println(res.Cached) // false

	// Trying again
	res = cli.GetGeoInfoFromString(ctx, "8.8.8.8")
	if err := res.Error; err != nil {
		log.Println(err)
		return
	}
	cli.Logger.Println(res.Cached) // true

	// Using an empty client, which comes with default http client and no cache
	// and no logs
	cli = &freeGeoIP.Client{}
	res = cli.GetGeoInfo(ctx, freeGeoIP.IP{8, 8, 8, 8})
	if err := res.Error; err != nil {
		log.Println(err)
		return
	}

	// You can use the `ICache` interface and provide you any of you cache
	// implementation or can use the library's in-memory (thread safe) with
	// or without expiry.
	cache := freeGeoIP.NewCache(freeGeoIP.NoCacheExpiration,
		func(ctx context.Context, ip freeGeoIP.IP) time.Duration {
			// check ip pattern
			if value := ctx.Value("IP_Skip_Pattern"); value != nil {
				if pat, ok := value.(string); ok {
					if strings.Contains(ip.String(), pat) {
						// always skip caching such ip patterns
						return freeGeoIP.SkipCache
					}
				}
			}
			return freeGeoIP.NoCacheExpiration
		},
	)

	// And you can even provide your own combination of arguments in client
	// by providing a self cache implementation for `freeGeoIP.ICache` or the
	// the http.Client or the log.Logger
	// The below call to NewCache will create a non expiry cache implementation
	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

Documentation

Overview

Package freeGeoIP or 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

You can use the package using the following command:

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.

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 request to pull 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 MIT license.(https://github.com/Shivam010/go-freeGeoIP/blob/master/LICENSE)

Example
package main

import (
	"context"
	"github.com/Shivam010/go-freeGeoIP"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"time"
)

var ctx = context.TODO()

func main() {

	// Using default client which comes with an in-memory cache implementation
	// with 24 Hour expiry and a http.Client timeout of 2 seconds and a default
	// `log.Logger`
	cli := freeGeoIP.DefaultClient()
	res := cli.GetGeoInfoFromString(ctx, "8.8.8.8")
	if err := res.Error; err != nil {
		log.Println(err)
		return
	}
	// first time retrieval and hence, not a cached output
	cli.Logger.Println(res.Cached) // false

	// Trying again
	res = cli.GetGeoInfoFromString(ctx, "8.8.8.8")
	if err := res.Error; err != nil {
		log.Println(err)
		return
	}
	cli.Logger.Println(res.Cached) // true

	// Using an empty client, which comes with default http client and no cache
	// and no logs
	cli = &freeGeoIP.Client{}
	res = cli.GetGeoInfo(ctx, freeGeoIP.IP{8, 8, 8, 8})
	if err := res.Error; err != nil {
		log.Println(err)
		return
	}

	// You can use the `ICache` interface and provide you any of you cache
	// implementation or can use the library's in-memory (thread safe) with
	// or without expiry.
	cache := freeGeoIP.NewCache(freeGeoIP.NoCacheExpiration,
		func(ctx context.Context, ip freeGeoIP.IP) time.Duration {
			// check ip pattern
			if value := ctx.Value("IP_Skip_Pattern"); value != nil {
				if pat, ok := value.(string); ok {
					if strings.Contains(ip.String(), pat) {
						// always skip caching such ip patterns
						return freeGeoIP.SkipCache
					}
				}
			}
			return freeGeoIP.NoCacheExpiration
		},
	)

	// And you can even provide your own combination of arguments in client
	// by providing a self cache implementation for `freeGeoIP.ICache` or the
	// the http.Client or the log.Logger
	// The below call to NewCache will create a non expiry cache implementation
	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
	}
}
Output:

Index

Examples

Constants

View Source
const (
	// DefaultCacheExpiry is the default value for _Cache expiry
	DefaultCacheExpiry = 24 * time.Hour
	// DefaultCacheExpiry is constant for specifying no expiry
	NoCacheExpiration = cache.NoExpiration
	// SkipCache is constant for explicitly denying cache hit. Mainly
	// to be used in CacheExpiryFunction for filtering some ip
	SkipCache = -1 << 63
)
View Source
const (
	ErrInternal     = _Error("freeGeoIp: something went wrong")
	ErrLimitReached = _Error("freeGeoIp: api limit reached")
	ErrNoResponse   = _Error("freeGeoIp: no information found")
	ErrCacheMissed  = _Error("cache: info not found")
)
View Source
const (
	Endpoint = "https://freegeoip.app/json/"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type CacheExpiryFunction

type CacheExpiryFunction func(ctx context.Context, ip IP) time.Duration

CacheExpiryFunction is the functional parameter for the Cache implementation to change expiry for certain IP set or context conditions.

type Client

type Client struct {
	Cache   ICache
	HttpCli *http.Client
	Logger  *log.Logger
}

Client is our Free GeoLocation information client. If Cache is not provided then will always make the http request to https://freegeoip.app/json/ If HttpCli is not provided then will always use http.DefaultClient And if Logger is not provided, then a noopLogger will be used

func DefaultClient

func DefaultClient() *Client

DefaultClient is the library default geo location client with an in-memory cache with a default expiry of 24 Hours and will set a total of 2 seconds timeout in http.Client, with the default inbuilt library logger.

func (*Client) GetGeoInfo

func (c *Client) GetGeoInfo(ctx context.Context, ip IP) Response

GetGeoInfo will return the free geolocation api response for the provided IP and uses the Cached response, if cache is used. For default empty Client behaviour see Client object description

func (*Client) GetGeoInfoFromString

func (c *Client) GetGeoInfoFromString(ctx context.Context, ip string) Response

GetGeoInfoFromString will return the API response for provided `ip` string It call the GetGeoInfo.

type ICache

type ICache interface {
	Set(ctx context.Context, info *Info)
	Get(ctx context.Context, ip IP) (*Info, error)
}

ICache is the custom cache interface used by the library. If Info is not found in the cache in Get, then the system default error should be returned i.e. `ErrCacheMissed` See it's default implementation: _Cache

func DefaultCache

func DefaultCache() ICache

DefaultCache is the default cache implementation with 24 Hours expiry

func NewCache

func NewCache(expiry time.Duration, expFn CacheExpiryFunction) ICache

NewCache is the constructor that returns the ICache implementation with the custom defined expiry duration or the `CacheExpiryFunction` to filter any selected ip set for expiry.

If expiry is set to SkipCache and expFn is also nil, the the NoopCache{} is returned. And if expiry is negative, then NoCacheExpiration will be used. Otherwise, provided functionality will continue. Note: If expFn is defined then the expiry duration will not be used, define carefully.

func NonExpiryCache

func NonExpiryCache() ICache

NonExpiryCache is the default cache implementation without any expiry

type IP

type IP net.IP

IP is a wrapper for net.IP

func ParseIP

func ParseIP(ip string) IP

func (*IP) MarshalJSON

func (ip *IP) MarshalJSON() ([]byte, error)

func (IP) Net

func (ip IP) Net() net.IP

func (IP) String

func (ip IP) String() string

func (*IP) UnmarshalJSON

func (ip *IP) UnmarshalJSON(b []byte) error

type Info

type Info struct {
	IP IP `json:"ip"`

	CountryCode string  `json:"country_code"`
	CountryName string  `json:"country_name"`
	RegionCode  string  `json:"region_code"`
	RegionName  string  `json:"region_name"`
	City        string  `json:"city"`
	ZipCode     string  `json:"zip_code"`
	MetroCode   float64 `json:"metro_code"`

	TimeZone *Location `json:"time_zone"`

	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
}

Info is the object specifying geo-location information obtained from the application https://freegeoip.app/

func Decoder

func Decoder(data []byte) (*Info, error)

type Location

type Location time.Location

Location is a wrapper for *time.Location

func LocationF

func LocationF(zone *time.Location) *Location

func (*Location) MarshalJSON

func (tz *Location) MarshalJSON() ([]byte, error)

func (*Location) String

func (tz *Location) String() string

func (*Location) Time

func (tz *Location) Time() *time.Location

func (*Location) UnmarshalJSON

func (tz *Location) UnmarshalJSON(b []byte) error

type MetaInfo

type MetaInfo struct {
	// duration in which limit will reset
	ResetIn time.Duration
	// total rate limit per hour
	Limit int64
	// remaining limit for the resetsIn duration
	Remaining int64
}

type NoopCache

type NoopCache struct{}

NoopCache empty cache implementation

func (NoopCache) Get

func (n NoopCache) Get(context.Context, IP) (*Info, error)

Get does nothing

func (NoopCache) Set

func (n NoopCache) Set(context.Context, *Info)

Set does nothing

type Response

type Response struct {
	// Info will contain the geo-location information about the IP provided in
	// request, and will be nil, if Error is not nil
	Info *Info
	// Error will contains any error if occurred during the retrieval, including
	// the limit reached error, `ErrLimitReached`. Otherwise will be nil
	Error error
	// Cached will be true if the Info response is retrieved from cached
	Cached bool
	// The MetaInfo may not have correct value if the geo info is retrieved from
	// cache, i.e. if Cached is true
	Meta *MetaInfo
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL