geolocation

package
v14.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 8 Imported by: 0

README

Geolocation

This middleware resolves the client's IP address to a location. It calls ip-api.com for the geolocation data and, when you ask for it, restcountries.com for the country's primary language. Results are cached in memory, so a repeat visitor costs no external call.

Features

  • Fetches geolocation information based on the client's IP address.
  • Optionally fetches the primary language of the country.
  • Customizable error handling.
  • In-memory caching for geolocation information.
Installation

To use the geolocation middleware, you need to import it into your Iris application:

import "github.com/kataras/iris/v14/middleware/geolocation"

Usage

Middleware Usage
package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/middleware/geolocation"
)

func main() {
	app := iris.New()
	app.Use(geolocation.New(geolocation.Options{}))

	app.Get("/", func(ctx iris.Context) {
		info := geolocation.Get(ctx)
		ctx.JSON(info)
	})

	app.Listen(":8080")
}
Options

geolocation.New takes a geolocation.Options value. The zero value is valid; every field below is optional.

  • APIKey: the API key for the ip-api.com API. When set (and LocationClient is not), the paid HTTPS endpoint is used. Defaults to an empty string.
  • LocationClient: a custom HTTP client for the location provider (ip-api.com by default). Useful for a self-hosted provider or a mock server in tests.
  • LanguageClient: a custom HTTP client for the language provider (restcountries.com by default).
  • DisableLanguage: skips fetching the primary language of the country.
  • Cache: the cache used to store the geolocation information. Defaults to an in-memory cache.
  • DisableCache: looks up every request instead of caching.

iris.WithErrorHandler is a middleware, not a geolocation option: it registers an error handler for the requests that follow it. Errors that may occur during the fetching of the geolocation information are reported through it.

API Key

The default rate limit for the free version is 45 requests per minute (1,440 requests daily). For more information on pricing and to see the available plans, visit IP-API Pricing. The paid plan offers unlimited requests and is very affordable compared to other services (e.g., ipgeolocation.io).

You can provide a custom API key for the ip-api.com API by setting the APIKey.

app.Use(geolocation.New(geolocation.Options{APIKey: "my-api-key"}))
Disable Language Fetching

You can disable fetching the primary language of the country by setting DisableLanguage.

app.Use(geolocation.New(geolocation.Options{DisableLanguage: true}))
Custom Error Handler

You can customize the error handling by implementing the func(iris.Context, error) function and registering it using the Application's or a Router's or a Route's Hadler's ContextOptions. All geolocation's middleware errors are of type geolocation.Err and can be checked using the errors.Is function.

errors below is github.com/kataras/iris/v14/rest/errors, which re-exports the standard errors.Is alongside the canonical error codes, so one import covers the check and the response.

errorHandler:= func(ctx iris.Context, err error) {
    if errors.Is(err , geolocation.Err) {
        // The error code carries the 401 and stops the chain.
        errors.Unauthenticated.Message(ctx, "geolocation lookup is not authorized")
        return
	}

    // [...rest of your error handling code...]
}
app.ContextOptions().ErrorHandler = errorHandler
app.Use(geolocation.New(geolocation.Options{}))
// [...]

Per-Router:

usersAPI := app.Router("/users")
usersAPI.ContextOptions().ErrorHandler = errorHandler
usersAPI.Use(geolocation.New(geolocation.Options{}))
usersAPI.Get("/", ...)
// [...]

Per-Route using the iris.WithErrorHandler middleware:

app.Get("/", iris.WithErrorHandler(errorHandler), geolocation.New(geolocation.Options{}), mainHandler)
// [...]
Cache

The geolocation middleware supports caching to store geolocation information and reduce the number of external API requests.

Default Memory Cache

By default, the middleware uses an in-memory cache with a dynamic maximum count based on the system's available memory. You can configure the cache with a maximum count of items. When the maximum count is reached, the cache will clean up the oldest items.

Custom Memory Cache

You can provide a custom maximum count for the memory cache:

app.Use(geolocation.New(geolocation.Options{Cache: cache.NewMemoryCache[geolocation.Info](11000)}))

where cache is github.com/kataras/iris/v14/core/pkg/cache.

Disable Cache

You can disable the cache by setting DisableCache:

app.Use(geolocation.New(geolocation.Options{DisableCache: true}))
Fetch Usage

You can also skip the middleware registration and fetch the geolocation information manually using the Fetch function:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/middleware/geolocation"
	"github.com/kataras/iris/v14/rest/errors"
)

func main() {
	app := iris.New()

	app.Get("/", func(ctx iris.Context) {
		info, err := geolocation.Fetch(ctx)
		if err != nil { // here you handle the error.
			errors.NotFound.Err(ctx, err)
			return
		}

		ctx.OK(info, nil)
	})

	app.Listen(":8080")
}
Output Example

Both examples will output the geolocation information in JSON format:

{
    "status": "success",
    "country": "Greece",
    "countryCode": "GR",
    "region": "G",
    "regionName": "North Greece",
    "city": "Xanthi",
    "zip": "",
    "lat": 38.6214,
    "lon": 21.4078,
    "timezone": "Europe/Athens",
    "isp": "Cosmote Mobile Telecommunication S.A",
    "org": "Cosmote Mobile Telecommunications S.A.",
    "as": "AS29247 Ote SA (Hellenic Telecommunications Organisation)",
    "query": "107.178.202.219",
    "language": "Greek"
}

Documentation

Overview

Package geolocation resolves the client's IP address to a country, region and city (and, optionally, the country's main language).

Its entry point is New(Options), which returns a Handler that stores an *Info on the Context; read it back with Get, or look one up on demand with Fetch. Free for non-commercial use, no API key required.

Index

Constants

This section is empty.

Variables

View Source
var Err = errors.New("geolocation error")

Err is the error returned when the geolocation information is not available. Usage:

if errors.Is(err, geolocation.Err) {
 // handle the error err.Error().
}

Functions

func New

func New(opts Options) context.Handler

New returns a new geolocation middleware (custom implementation) based on the information retrieved by ip-api.com. It fetches the geolocation information for the client's IP address and stores it to the Iris Context. Retrieve the geolocation information using the `Get` function.

The default rate limit is 45 requests per minute (1,440 daily) for free version. Navigate through https://members.ip-api.com/#pricing to see the prices and the rate limits. Its paid plan with unlimited requests is very cheap compared to the rest (e.g. ipgeolocation.io).

func NewMemoryCache

func NewMemoryCache(maxCount int) cache.Cache[Info]

NewMemoryCache creates a new MemoryCache with the specified maximum count. if maxCount is zero or negative, a default value is calculated based on the available memory.

Types

type Info

type Info struct {
	Status      string  `json:"status"`
	Country     string  `json:"country"`
	CountryCode string  `json:"countryCode"`
	Region      string  `json:"region"`
	RegionName  string  `json:"regionName"`
	City        string  `json:"city"`
	Zip         string  `json:"zip"`
	Lat         float64 `json:"lat"`
	Lon         float64 `json:"lon"`
	Timezone    string  `json:"timezone"`
	Isp         string  `json:"isp"`
	Org         string  `json:"org"`
	As          string  `json:"as"`
	Query       string  `json:"query"`
	Language    string  `json:"language"`
}

Info represents the geolocation information for an IP address.

func Fetch

func Fetch(ctx *context.Context) (*Info, error)

Fetch returns the geolocation information for the client's IP address. It returns the value already stored in the Iris Context, otherwise it performs a live lookup with the default options and stores the result in the Context. It returns an error if the information is not available. Use the `New` function to register the geolocation middleware or the `Get` function to read the stored value without performing a lookup.

func Get

func Get(ctx *context.Context) *Info

Get returns the geolocation information from the Iris Context.

type Options

type Options struct {
	// APIKey, when not empty and LocationClient is nil, points the location
	// lookup at the paid HTTPS endpoint (https://pro.ip-api.com/json) with this
	// key. It is ignored when LocationClient is set.
	//
	// Defaults to empty: the free, plaintext-HTTP endpoint is used.
	APIKey string `yaml:"APIKey"`

	// LocationClient is the HTTP client used to fetch geolocation information from ip-api.com.
	//
	// Absolutely free (with rate limiting) for non-commercial use, no API key required.
	//
	// Defaults to a client for http://ip-api.com/json rate-limited to 45 requests
	// per minute (or the pro endpoint when APIKey is set).
	LocationClient *client.Client `yaml:"-"`

	// LanguageClient is the HTTP client used to fetch the language information from restcountries.com.
	// Please consider donating if you are using it a lot.
	//
	// Defaults to a client for https://restcountries.com/v3.1/alpha.
	// Set DisableLanguage to skip the language lookup entirely.
	LanguageClient *client.Client `yaml:"-"`

	// DisableLanguage skips the country-language lookup, so Info.Language is
	// left empty and no request is sent to restcountries.com.
	//
	// Defaults to false.
	DisableLanguage bool `yaml:"DisableLanguage"`

	// Cache is the cache used to store the geolocation information.
	//
	// Defaults to cache.NewMemoryCache[Info](0).
	// Set DisableCache to look up every request.
	Cache cache.Cache[Info] `yaml:"-"`

	// DisableCache turns the lookup cache off, so every request performs a live
	// lookup. Mind the provider's rate limit.
	//
	// Defaults to false.
	DisableCache bool `yaml:"DisableCache"`
}

Options is the configuration for the geolocation middleware. The zero value is valid and uses the free ip-api.com endpoint, restcountries.com for the language and an in-memory cache with no expiration.

It uses two different clients for fetching the geolocation information and the country's main language:

  • ip-api.com API is used to fetch the geolocation information for the IP address,
  • restcountries.com API is used to fetch the language for the country code.

Jump to

Keyboard shortcuts

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