geoip

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 7 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package geoip resolves an IP address to a place using a local MaxMind-format (.mmdb) database. Lookups are fully offline: the memory-mapped file IS the lookup, so there is no per-address network call and no cache to keep coherent with anything.

Offline is a requirement here, not a preference: the addresses handed to this package are often a caller's own untrusted visitors (including people who never authenticated), so sending them to a third party to be geolocated would hand that list to somebody else.

One Reader reads either of the two common free database schemas, because they disagree about the shape of the same field:

  • MaxMind GeoLite2 / GeoIP2 / DB-IP Lite: nested objects, where "country" is a map {iso_code, names:{en:...}}, plus "city", "subdivisions" and a "location" block {latitude, longitude, accuracy_radius} on city-level databases.
  • ipinfo Lite: flat strings, where "country" is the country NAME and "country_code" is the ISO code; country granularity only.

They collide on the "country" key (map vs. string), so a record is decoded into a generic map and branched on the runtime type rather than into one fixed struct. That also means a future MaxMind-compatible database works without a change here.

This package knows nothing about who is asking or why: it maps an IP string to a Location and nothing else. Anything above that — whether a lookup is even attempted, what a caller does with the result, how failures are surfaced to an operator — is the caller's concern, not this package's.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsResolvable

func IsResolvable(ip string) bool

IsResolvable reports whether ip is a routable, unicast address worth looking up. A loopback, private (RFC 1918 / ULA), link-local, unspecified, or multicast address is never in a geolocation database, and looking one up would only produce an empty answer more slowly. Works for both IPv4 and IPv6.

Types

type DBInfo

type DBInfo struct {
	Type        string `json:"type"`        // Metadata.DatabaseType, e.g. "GeoLite2-City"
	BuildEpoch  uint   `json:"build_epoch"` // unix seconds the database was built
	Granularity string `json:"granularity"` // "city" or "country"
}

DBInfo describes a loaded database, e.g. for an admin status view.

type LocalizedNames added in v0.6.0

type LocalizedNames struct {
	Country map[string]string `json:"country,omitempty"`
	Region  map[string]string `json:"region,omitempty"`
	City    map[string]string `json:"city,omitempty"`
}

LocalizedNames groups the optional locale-to-name maps carried by MaxMind records. Locale keys are BCP 47-like database keys such as en or zh-CN.

type Location

type Location struct {
	CountryCode string `json:"country_code,omitempty"` // ISO 3166-1 alpha-2, upper-cased
	Country     string `json:"country,omitempty"`
	Region      string `json:"region,omitempty"` // state / province
	City        string `json:"city,omitempty"`
	// RegionCode is the region part of the first subdivision's ISO 3166-2
	// code, without the country prefix ("GD", not "CN-GD"), upper-cased: the
	// code for the subdivision Region names, when Region came from one.
	RegionCode string  `json:"region_code,omitempty"`
	Latitude   float64 `json:"latitude,omitempty"`  // WGS84 degrees, -90..90
	Longitude  float64 `json:"longitude,omitempty"` // WGS84 degrees, -180..180
	// AccuracyRadiusKm is the radius around (Latitude, Longitude) within
	// which the database expects the address to be. 0 means the database
	// gave none (DB-IP Lite documents none), not that the point is exact; it
	// is always 0 when there are no coordinates.
	AccuracyRadiusKm int `json:"accuracy_radius_km,omitempty"`
	// LocalizedNames preserves alternate names supplied by a MaxMind-format
	// database. It is omitted when the record has no alternate language, so
	// English-only and flat-schema responses keep their original JSON shape.
	LocalizedNames *LocalizedNames `json:"localized_names,omitempty"`
}

Location is what a lookup can say about an address. Every field is optional: a country-level database fills only CountryCode and Country, and an address that is not in the database (or was never looked up) fills none.

RegionCode, Latitude, Longitude and AccuracyRadiusKm are read only from the MaxMind schema's "subdivisions" and "location" keys, which city-level databases carry, and not every such database fills all four (the README lists which fills which). They were added after the first four fields, all omitempty, so a Location without them marshals to exactly the JSON it did before they existed.

Latitude and Longitude are a pair, set together or not at all, and (0, 0) means there are none. They are where the database places the network, not where the device is: MaxMind documents them as not precise, standing for a larger area rather than a location, and AccuracyRadiusKm is that area's radius when the database gives one. Deciding what a distance between two lookups means (travel, sharing, nothing) is the caller's policy, not this package's. In JSON a coordinate that is exactly 0 is dropped by omitempty like any other zero, so a point on the equator arrives with "longitude" alone; read the missing one as 0.

func (Location) Empty

func (l Location) Empty() bool

Empty reports whether the lookup found nothing worth showing. Useful for callers that want to distinguish "resolved to nothing" from "has a value" without comparing every field themselves.

It looks only at the four place-name fields. A Location holding coordinates or a RegionCode but no name still reports Empty, as it would have before those fields existed, so adding them changed no caller's answer.

type Option

type Option func(*Watcher)

Option configures a Watcher.

func WithEnabled

func WithEnabled(enabled bool) Option

WithEnabled sets whether the Watcher resolves addresses at all. A disabled Watcher never opens its file and Lookup always returns an empty Location — this lets a caller wire in an on/off setting without branching around every call site. Enabled by default.

func WithPath

func WithPath(path string) Option

WithPath sets the initial database file to watch. Equivalent to calling SetPath right after NewWatcher.

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

Reader wraps an open .mmdb database. Safe for concurrent Lookup calls (the underlying maxminddb.Reader is) — a nil *Reader is also safe to call every method on, answering as "no database loaded" rather than panicking, so a caller that has not opened one yet does not need a nil check at every call site. The caller owns the Reader's lifecycle (open, close, reload).

func Open

func Open(path string) (*Reader, error)

Open opens an .mmdb file.

func (*Reader) Close

func (r *Reader) Close() error

Close releases the database. Safe to call on a nil Reader.

func (*Reader) Info

func (r *Reader) Info() DBInfo

Info returns metadata about the loaded database.

func (*Reader) Lookup

func (r *Reader) Lookup(ip string) (Location, error)

Lookup resolves one address. An unparseable, private, or unmapped address returns a zero Location and a nil error, deliberately: "we do not know where this is" is the ordinary answer for a LAN address or a miss, not a failure, and making every caller distinguish it from a real error would put the same branch at every call site to reach the same result. A non-nil error means the database itself could not be read (a corrupt file, for example) — not that the address was not found.

type Status

type Status struct {
	Enabled bool   `json:"enabled"`
	Path    string `json:"path"`
	Loaded  bool   `json:"loaded"`
	Info    DBInfo `json:"info"`
	Error   string `json:"error,omitempty"` // set when Path is non-empty but failed to open
}

Status reports the Watcher's current state, for a caller's own admin or health view.

type Watcher

type Watcher struct {
	// contains filtered or unexported fields
}

Watcher serves lookups against a single .mmdb file, hot-reloading it when the file on disk changes (a new build, a fresh download, an operator dropping in a replacement) without a caller restart.

It deliberately does not scan a directory or choose between several candidate files — "which database is active" is a policy decision that belongs to the caller (a setting, an admin's pick, "newest wins", ...). Watcher only answers "reload the one file I was told about, when it changes." Point it at a different file at any time with SetPath.

A nil *Watcher is safe to call every method on: it behaves like a disabled Watcher with no database loaded.

The watched file MUST be replaced by an atomic rename (write the new content to a temp file beside it, then os.Rename over the watched path), never by truncating and rewriting the same path in place. Watcher's internal lock only protects its own reader pointer, not the bytes underneath an already memory-mapped file: an in-place rewrite can hand a concurrent, in-flight Lookup a SIGBUS. A rename swaps the directory entry to a new inode, so an in-flight Lookup keeps reading the old (now unlinked but still open and unmodified) inode safely to completion. Both PSP's and RP's own database updaters already replace files this way.

func NewWatcher

func NewWatcher(opts ...Option) *Watcher

NewWatcher creates a Watcher. It does not open the database file yet — the first Lookup or Refresh does, so a Watcher can be constructed before its target file exists.

func (*Watcher) Close

func (w *Watcher) Close() error

Close releases the currently loaded database, if any. The watched path is kept: a subsequent Lookup reopens it rather than staying dark, since Close is meant for releasing resources (e.g. at shutdown), not for disabling the Watcher — use SetEnabled(false) for that.

func (*Watcher) Lookup

func (w *Watcher) Lookup(ip string) Location

Lookup resolves one address against the current database, reloading it first if the underlying file has changed. Like Reader.Lookup, an unresolvable, unmapped, or (here) disabled/unloaded case is a zero Location with no error — this method never fails, so a caller resolving many addresses never needs per-address error handling. Use Status to observe whether the database is actually loaded.

The reload check and the actual database read happen under the same read lock: maxminddb.Reader.Close() munmaps the file, so a Lookup that captured a reader pointer and then read it AFTER releasing the lock could race a concurrent reload/Close and dereference already-unmapped memory — a SIGSEGV nothing in Go can recover from. Holding RLock across the read (not just across the pointer fetch) is what rules that out; only the rare reload briefly blocks a concurrent Lookup, never the other way around.

func (*Watcher) Refresh

func (w *Watcher) Refresh()

Refresh makes sure the watched file has been (re)opened if it changed, without performing a lookup. Callers that only want to force a reload after replacing the file (rather than waiting for the next Lookup) can call this.

func (*Watcher) SetEnabled

func (w *Watcher) SetEnabled(enabled bool)

SetEnabled turns resolution on or off at runtime.

func (*Watcher) SetPath

func (w *Watcher) SetPath(path string)

SetPath changes which file the Watcher serves. Takes effect on the next Lookup or Refresh; the previously open database (if any) stays in use until then, so callers see no gap.

func (*Watcher) Status

func (w *Watcher) Status() Status

Status returns a snapshot of the Watcher's state without forcing a reload check (it reports whatever is currently loaded).

Jump to

Keyboard shortcuts

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