Movatterモバイル変換


[0]ホーム

URL:


maxminddb

packagemodule
v2.0.0Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2025 License:ISCImports:14Imported by:22

Details

Repository

github.com/oschwald/maxminddb-golang

Links

README

MaxMind DB Reader for Go

Go Reference

This is a Go reader for the MaxMind DB format. Although this can be used toreadGeoLite2andGeoIP2 databases,geoip2 provides a higher-level APIfor doing so.

This is not an official MaxMind API.

Installation

go get github.com/oschwald/maxminddb-golang/v2

Version 2.0 Features

Version 2.0 includes significant improvements:

  • Modern API: Usesnetip.Addr instead ofnet.IP for better performance
  • Custom Unmarshaling: ImplementUnmarshaler interface forzero-allocation decoding
  • Network Iteration: Iterate over all networks in a database withNetworks() andNetworksWithin()
  • Enhanced Performance: Optimized data structures and decoding paths
  • Go 1.24+ Support: Takes advantage of modern Go features includingiterators
  • Better Error Handling: More detailed error types and improved debugging
  • Integrity Checks: Validate databases withReader.Verify() and accessmetadata helpers such asMetadata.BuildTime()

SeeMIGRATION.md for guidance on updating existing v1 code.

Quick Start

package mainimport ("fmt""log""net/netip""github.com/oschwald/maxminddb-golang/v2")func main() {db, err := maxminddb.Open("GeoLite2-City.mmdb")if err != nil {log.Fatal(err)}defer db.Close()ip, err := netip.ParseAddr("81.2.69.142")if err != nil {log.Fatal(err)}var record struct {Country struct {ISOCode string            `maxminddb:"iso_code"`Names   map[string]string `maxminddb:"names"`} `maxminddb:"country"`City struct {Names map[string]string `maxminddb:"names"`} `maxminddb:"city"`}err = db.Lookup(ip).Decode(&record)if err != nil {log.Fatal(err)}fmt.Printf("Country: %s (%s)\n", record.Country.Names["en"], record.Country.ISOCode)fmt.Printf("City: %s\n", record.City.Names["en"])}

Usage Patterns

Basic Lookup
db, err := maxminddb.Open("GeoLite2-City.mmdb")if err != nil {log.Fatal(err)}defer db.Close()var record anyip := netip.MustParseAddr("1.2.3.4")err = db.Lookup(ip).Decode(&record)
Custom Struct Decoding
type City struct {Country struct {ISOCode string `maxminddb:"iso_code"`Names   struct {English string `maxminddb:"en"`German  string `maxminddb:"de"`} `maxminddb:"names"`} `maxminddb:"country"`}var city Cityerr = db.Lookup(ip).Decode(&city)
High-Performance Custom Unmarshaling
type FastCity struct {CountryISO stringCityName   string}func (c *FastCity) UnmarshalMaxMindDB(d *maxminddb.Decoder) error {mapIter, size, err := d.ReadMap()if err != nil {return err}// Pre-allocate with correct capacity for better performance_ = size // Use for pre-allocation if storing map datafor key, err := range mapIter {if err != nil {return err}switch string(key) {case "country":countryIter, _, err := d.ReadMap()if err != nil {return err}for countryKey, countryErr := range countryIter {if countryErr != nil {return countryErr}if string(countryKey) == "iso_code" {c.CountryISO, err = d.ReadString()if err != nil {return err}} else {if err := d.SkipValue(); err != nil {return err}}}default:if err := d.SkipValue(); err != nil {return err}}}return nil}
Network Iteration
// Iterate over all networks in the databasefor result := range db.Networks() {var record struct {Country struct {ISOCode string `maxminddb:"iso_code"`} `maxminddb:"country"`}err := result.Decode(&record)if err != nil {log.Fatal(err)}fmt.Printf("%s: %s\n", result.Prefix(), record.Country.ISOCode)}// Iterate over networks within a specific prefixprefix := netip.MustParsePrefix("192.168.0.0/16")for result := range db.NetworksWithin(prefix) {// Process networks within 192.168.0.0/16}
Path-Based Decoding
var countryCode stringerr = db.Lookup(ip).DecodePath(&countryCode, "country", "iso_code")var cityName stringerr = db.Lookup(ip).DecodePath(&cityName, "city", "names", "en")

Supported Database Types

This library supportsall MaxMind DB (.mmdb) format databases, including:

MaxMind Official Databases:

  • GeoLite/GeoIP City: Comprehensive location data including city, country,subdivisions
  • GeoLite/GeoIP Country: Country-level geolocation data
  • GeoLite ASN: Autonomous System Number and organization data
  • GeoIP Anonymous IP: Anonymous network and proxy detection
  • GeoIP Enterprise: Enhanced City data with additional business fields
  • GeoIP ISP: Internet service provider information
  • GeoIP Domain: Second-level domain data
  • GeoIP Connection Type: Connection type identification

Third-Party Databases:

  • DB-IP databases: Compatible with DB-IP's .mmdb format databases
  • IPinfo databases: Works with IPinfo's MaxMind DB format files
  • Custom databases: Any database following the MaxMind DB file formatspecification

The library is format-agnostic and will work with any valid .mmdb fileregardless of the data provider.

Performance Tips

  1. Reuse Reader instances: TheReader is thread-safe and should be reusedacross goroutines
  2. Use specific structs: Only decode the fields you need rather than usingany
  3. Implement Unmarshaler: For high-throughput applications, implementcustom unmarshaling
  4. Consider caching: UseResult.Offset() as a cache key for databaserecords

Getting Database Files

Free GeoLite2 Databases

Download fromMaxMind's GeoLite page.

Documentation

Requirements

  • Go 1.24 or later
  • MaxMind DB file in .mmdb format

Contributing

Contributions welcome! Please fork the repository and open a pull request withyour changes.

License

This is free software, licensed under the ISC License.

Documentation

Overview

Package maxminddb provides a reader for the MaxMind DB file format.

This package provides an API for reading MaxMind GeoIP2 and GeoLite2databases in the MaxMind DB file format (.mmdb files). The API is designedto be simple to use while providing high performance for IP geolocationlookups and related data.

Basic Usage

The most common use case is looking up geolocation data for an IP address:

db, err := maxminddb.Open("GeoLite2-City.mmdb")if err != nil {log.Fatal(err)}defer db.Close()ip, err := netip.ParseAddr("81.2.69.142")if err != nil {log.Fatal(err)}var record struct {Country struct {ISOCode string `maxminddb:"iso_code"`Names   map[string]string `maxminddb:"names"`} `maxminddb:"country"`City struct {Names map[string]string `maxminddb:"names"`} `maxminddb:"city"`}err = db.Lookup(ip).Decode(&record)if err != nil {log.Fatal(err)}fmt.Printf("Country: %s\n", record.Country.Names["en"])fmt.Printf("City: %s\n", record.City.Names["en"])

Database Types

This library supports all MaxMind database types:

  • GeoLite2/GeoIP2 City: Comprehensive location data including city, country, subdivisions
  • GeoLite2/GeoIP2 Country: Country-level geolocation data
  • GeoLite2 ASN: Autonomous System Number and organization data
  • GeoIP2 Anonymous IP: Anonymous network and proxy detection
  • GeoIP2 Enterprise: Enhanced City data with additional business fields
  • GeoIP2 ISP: Internet service provider information
  • GeoIP2 Domain: Second-level domain data
  • GeoIP2 Connection Type: Connection type identification

Performance

For maximum performance in high-throughput applications, consider:

  1. Using custom struct types that only include the fields you need
  2. Implementing the Unmarshaler interface for custom decoding
  3. Reusing the Reader instance across multiple goroutines (it's thread-safe)

Custom Unmarshaling

For custom decoding logic, you can implement the mmdbdata.Unmarshaler interface,similar to how encoding/json's json.Unmarshaler works. Types implementing thisinterface will automatically use custom decoding logic when used with Reader.Lookup:

type FastCity struct {CountryISO stringCityName   string}func (c *FastCity) UnmarshalMaxMindDB(d *mmdbdata.Decoder) error {// Custom decoding logic using d.ReadMap(), d.ReadString(), etc.// Allows fine-grained control over how MaxMind DB data is decoded// See mmdbdata package documentation and ExampleUnmarshaler for complete examples}

Network Iteration

You can iterate over all networks in a database:

for result := range db.Networks() {var record struct {Country struct {ISOCode string `maxminddb:"iso_code"`} `maxminddb:"country"`}err := result.Decode(&record)if err != nil {log.Fatal(err)}fmt.Printf("%s: %s\n", result.Prefix(), record.Country.ISOCode)}

Database Files

MaxMind provides both free (GeoLite2) and commercial (GeoIP2) databases:

Thread Safety

All Reader methods are thread-safe. The Reader can be safely shared acrossmultiple goroutines.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

typeInvalidDatabaseError

type InvalidDatabaseError =mmdberrors.InvalidDatabaseError

InvalidDatabaseError is returned when the database contains invalid dataand cannot be parsed.

typeMetadata

type Metadata struct {// Description contains localized database descriptions.// Keys are language codes (e.g., "en", "zh-CN"), values are UTF-8 descriptions.Description map[string]string `maxminddb:"description"`// DatabaseType indicates the structure of data records associated with IP addresses.// Names starting with "GeoIP" are reserved for MaxMind databases.DatabaseTypestring `maxminddb:"database_type"`// Languages lists locale codes for which this database may contain localized data.// Records should not contain localized data for locales not in this array.Languages []string `maxminddb:"languages"`// BinaryFormatMajorVersion is the major version of the MaxMind DB binary format.// Current supported version is 2.BinaryFormatMajorVersionuint `maxminddb:"binary_format_major_version"`// BinaryFormatMinorVersion is the minor version of the MaxMind DB binary format.// Current supported version is 0.BinaryFormatMinorVersionuint `maxminddb:"binary_format_minor_version"`// BuildEpoch contains the database build timestamp as Unix epoch seconds.// Use BuildTime() method for a time.Time representation.BuildEpochuint `maxminddb:"build_epoch"`// IPVersion indicates the IP version support://   4: IPv4 addresses only//   6: Both IPv4 and IPv6 addressesIPVersionuint `maxminddb:"ip_version"`// NodeCount is the number of nodes in the search tree.NodeCountuint `maxminddb:"node_count"`// RecordSize is the size in bits of each record in the search tree.// Valid values are 24, 28, or 32.RecordSizeuint `maxminddb:"record_size"`}

Metadata holds the metadata decoded from the MaxMind DB file.

Key fields include:

  • DatabaseType: indicates the structure of data records (e.g., "GeoIP2-City")
  • Description: localized descriptions in various languages
  • Languages: locale codes for which the database may contain localized data
  • BuildEpoch: database build timestamp as Unix epoch seconds
  • IPVersion: supported IP version (4 for IPv4-only, 6 for IPv4/IPv6)
  • NodeCount: number of nodes in the search tree
  • RecordSize: size in bits of each record in the search tree (24, 28, or 32)

For detailed field descriptions, see the MaxMind DB specification:https://maxmind.github.io/MaxMind-DB/

func (Metadata)BuildTime

func (mMetadata) BuildTime()time.Time

BuildTime returns the database build time as a time.Time.This is a convenience method that converts the BuildEpoch fieldfrom Unix epoch seconds to a time.Time value.

typeNetworksOption

type NetworksOption func(*networkOptions)

NetworksOption are options for Networks and NetworksWithin.

funcIncludeAliasedNetworks

func IncludeAliasedNetworks()NetworksOption

IncludeAliasedNetworks is an option for Networks and NetworksWithinthat makes them iterate over aliases of the IPv4 subtree in an IPv6database, e.g., ::ffff:0:0/96, 2001::/32, and 2002::/16.

funcIncludeNetworksWithoutData

func IncludeNetworksWithoutData()NetworksOption

IncludeNetworksWithoutData is an option for Networks and NetworksWithinthat makes them include networks without any data in the iteration.

funcSkipEmptyValues

func SkipEmptyValues()NetworksOption

SkipEmptyValues is an option for Networks and NetworksWithin that makesthem skip networks whose data is an empty map or empty array. This isuseful for databases that store empty maps or arrays for records withoutmeaningful data, allowing iteration over only records with actual content.

Example

This example demonstrates how to use SkipEmptyValues to iterate only overnetworks that have actual data, skipping those with empty maps or arrays.

db, err := maxminddb.Open("test-data/test-data/GeoIP2-Anonymous-IP-Test.mmdb")if err != nil {log.Fatal(err)}defer db.Close()// Without SkipEmptyValues, you get all networks including empty onesfmt.Println("All networks:")count := 0for result := range db.Networks() {if result.Err() != nil {log.Panic(result.Err())}count++if count > 10 {fmt.Printf("... (%d more networks, many with empty data)\n", 529-count)break}var record map[string]anyerr := result.Decode(&record)if err != nil {log.Panic(err)}if len(record) == 0 {fmt.Printf("%s: (empty)\n", result.Prefix())} else {fmt.Printf("%s: %v\n", result.Prefix(), record)}}fmt.Println("\nOnly networks with data:")// With SkipEmptyValues, you only get networks with actual datafor result := range db.Networks(maxminddb.SkipEmptyValues()) {if result.Err() != nil {log.Panic(result.Err())}var record map[string]anyerr := result.Decode(&record)if err != nil {log.Panic(result.Err())}fmt.Printf("%s: %v\n", result.Prefix(), record)}
Output:All networks:1.0.0.0/15: (empty)1.2.0.0/16: map[is_anonymous:true is_anonymous_vpn:true]1.3.0.0/16: (empty)1.4.0.0/14: (empty)1.8.0.0/13: (empty)1.16.0.0/12: (empty)1.32.0.0/11: (empty)1.64.0.0/11: (empty)1.96.0.0/12: (empty)1.112.0.0/13: (empty)... (518 more networks, many with empty data)Only networks with data:1.2.0.0/16: map[is_anonymous:true is_anonymous_vpn:true]1.124.213.1/32: map[is_anonymous:true is_anonymous_vpn:true is_tor_exit_node:true]65.0.0.0/13: map[is_anonymous:true is_tor_exit_node:true]71.160.223.0/24: map[is_anonymous:true is_hosting_provider:true]81.2.69.0/24: map[is_anonymous:true is_anonymous_vpn:true is_hosting_provider:true is_public_proxy:true is_residential_proxy:true is_tor_exit_node:true]186.30.236.0/24: map[is_anonymous:true is_public_proxy:true]abcd:1000::/112: map[is_anonymous:true is_public_proxy:true]

typeReader

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

Reader holds the data corresponding to the MaxMind DB file. Its only publicfield is Metadata, which contains the metadata from the MaxMind DB file.

All of the methods on Reader are thread-safe. The struct may be safelyshared across goroutines.

funcOpen

func Open(filestring, options ...ReaderOption) (*Reader,error)

Open takes a string path to a MaxMind DB file and any options. It returns aReader structure or an error. The database file is opened using a memorymap on supported platforms. On platforms without memory map support, suchas WebAssembly or Google App Engine, or if the memory map attempt failsdue to lack of support from the filesystem, the database is loaded into memory.Use the Close method on the Reader object to return the resources to the system.

funcOpenBytes

func OpenBytes(buffer []byte, options ...ReaderOption) (*Reader,error)

OpenBytes takes a byte slice corresponding to a MaxMind DB file and anyoptions. It returns a Reader structure or an error.

func (*Reader)Close

func (r *Reader) Close()error

Close returns the resources used by the database to the system.

func (*Reader)Lookup

func (r *Reader) Lookup(ipnetip.Addr)Result

Lookup retrieves the database record for ip and returns a Result, which canbe used to decode the data.

Example (Interface)

This example demonstrates how to decode to an any.

db, err := maxminddb.Open("test-data/test-data/GeoIP2-City-Test.mmdb")if err != nil {log.Fatal(err)}defer db.Close()addr := netip.MustParseAddr("81.2.69.142")var record anyerr = db.Lookup(addr).Decode(&record)if err != nil {log.Panic(err)}fmt.Printf("%v", record)
Output:map[city:map[geoname_id:2643743 names:map[de:London en:London es:Londres fr:Londres ja:ロンドン pt-BR:Londres ru:Лондон]] continent:map[code:EU geoname_id:6255148 names:map[de:Europa en:Europe es:Europa fr:Europe ja:ヨーロッパ pt-BR:Europa ru:Европа zh-CN:欧洲]] country:map[geoname_id:2635167 iso_code:GB names:map[de:Vereinigtes Königreich en:United Kingdom es:Reino Unido fr:Royaume-Uni ja:イギリス pt-BR:Reino Unido ru:Великобритания zh-CN:英国]] location:map[accuracy_radius:10 latitude:51.5142 longitude:-0.0931 time_zone:Europe/London] registered_country:map[geoname_id:6252001 iso_code:US names:map[de:USA en:United States es:Estados Unidos fr:États-Unis ja:アメリカ合衆国 pt-BR:Estados Unidos ru:США zh-CN:美国]] subdivisions:[map[geoname_id:6269131 iso_code:ENG names:map[en:England es:Inglaterra fr:Angleterre pt-BR:Inglaterra]]]]
Example (Struct)

This example shows how to decode to a struct.

db, err := maxminddb.Open("test-data/test-data/GeoIP2-City-Test.mmdb")if err != nil {log.Fatal(err)}defer db.Close()addr := netip.MustParseAddr("81.2.69.142")var record struct {Country struct {ISOCode string `maxminddb:"iso_code"`} `maxminddb:"country"`} // Or any appropriate structerr = db.Lookup(addr).Decode(&record)if err != nil {log.Panic(err)}fmt.Print(record.Country.ISOCode)
Output:GB

func (*Reader)LookupOffset

func (r *Reader) LookupOffset(offsetuintptr)Result

LookupOffset returns the Result for the specified offset. Note thatnetip.Prefix returned by Networks will be invalid when using LookupOffset.

func (*Reader)Networks

func (r *Reader) Networks(options ...NetworksOption)iter.Seq[Result]

Networks returns an iterator that can be used to traverse the networks inthe database.

Please note that a MaxMind DB may map IPv4 networks into several locationsin an IPv6 database. This iterator will only iterate over these once bydefault. To iterate over all the IPv4 network locations, use theIncludeAliasedNetworks option.

Networks without data are excluded by default. To include them, useIncludeNetworksWithoutData.

Example

This example demonstrates how to iterate over all networks in thedatabase.

db, err := maxminddb.Open("test-data/test-data/GeoIP2-Connection-Type-Test.mmdb")if err != nil {log.Fatal(err)}defer db.Close()for result := range db.Networks() {record := struct {ConnectionType string `maxminddb:"connection_type"`}{}err := result.Decode(&record)if err != nil {log.Panic(err)}fmt.Printf("%s: %s\n", result.Prefix(), record.ConnectionType)}
Output:1.0.0.0/24: Cable/DSL1.0.1.0/24: Cellular1.0.2.0/23: Cable/DSL1.0.4.0/22: Cable/DSL1.0.8.0/21: Cable/DSL1.0.16.0/20: Cable/DSL1.0.32.0/19: Cable/DSL1.0.64.0/18: Cable/DSL1.0.128.0/17: Cable/DSL2.125.160.216/29: Cable/DSL67.43.156.0/24: Cellular80.214.0.0/20: Cellular96.1.0.0/16: Cable/DSL96.10.0.0/15: Cable/DSL96.69.0.0/16: Cable/DSL96.94.0.0/15: Cable/DSL108.96.0.0/11: Cellular149.101.100.0/28: Cellular175.16.199.0/24: Cable/DSL187.156.138.0/24: Cable/DSL201.243.200.0/24: Corporate207.179.48.0/20: Cellular216.160.83.56/29: Corporate2003::/24: Cable/DSL

func (*Reader)NetworksWithin

func (r *Reader) NetworksWithin(prefixnetip.Prefix, options ...NetworksOption)iter.Seq[Result]

NetworksWithin returns an iterator that can be used to traverse the networksin the database which are contained in a given prefix.

Please note that a MaxMind DB may map IPv4 networks into several locationsin an IPv6 database. This iterator will only iterate over these once bydefault. To iterate over all the IPv4 network locations, use theIncludeAliasedNetworks option.

If the provided prefix is contained within a network in the database, theiterator will iterate over exactly one network, the containing network.

Networks without data are excluded by default. To include them, useIncludeNetworksWithoutData.

Example

This example demonstrates how to iterate over all networks in thedatabase which are contained within an arbitrary network.

db, err := maxminddb.Open("test-data/test-data/GeoIP2-Connection-Type-Test.mmdb")if err != nil {log.Fatal(err)}defer db.Close()prefix, err := netip.ParsePrefix("1.0.0.0/8")if err != nil {log.Panic(err)}for result := range db.NetworksWithin(prefix) {record := struct {ConnectionType string `maxminddb:"connection_type"`}{}err := result.Decode(&record)if err != nil {log.Panic(err)}fmt.Printf("%s: %s\n", result.Prefix(), record.ConnectionType)}
Output:1.0.0.0/24: Cable/DSL1.0.1.0/24: Cellular1.0.2.0/23: Cable/DSL1.0.4.0/22: Cable/DSL1.0.8.0/21: Cable/DSL1.0.16.0/20: Cable/DSL1.0.32.0/19: Cable/DSL1.0.64.0/18: Cable/DSL1.0.128.0/17: Cable/DSL

func (*Reader)Verify

func (r *Reader) Verify()error

Verify performs comprehensive validation of the MaxMind DB file.

This method validates:

  • Metadata section: format versions, required fields, and value constraints
  • Search tree: traverses all networks to verify tree structure integrity
  • Data section separator: validates the 16-byte separator between tree and data
  • Data section: verifies all data records referenced by the search tree

The verifier is stricter than the MaxMind DB specification and may returnerrors on some databases that are still readable by normal operations.This method is useful for:

  • Validating database files after download or generation
  • Debugging database corruption issues
  • Ensuring database integrity in critical applications

Note: Verification traverses the entire database and may be slow on large files.The method is thread-safe and can be called on an active Reader.

Example

This example demonstrates how to validate a MaxMind DB file and access metadata.

db, err := maxminddb.Open("test-data/test-data/GeoIP2-City-Test.mmdb")if err != nil {log.Fatal(err)}defer db.Close()// Verify database integrityif err := db.Verify(); err != nil {log.Printf("Database validation failed: %v", err)return}// Access metadata informationmetadata := db.Metadatafmt.Printf("Database type: %s\n", metadata.DatabaseType)fmt.Printf("Build time: %s\n", metadata.BuildTime().UTC().Format("2006-01-02 15:04:05"))fmt.Printf("IP version: IPv%d\n", metadata.IPVersion)fmt.Printf("Languages: %v\n", metadata.Languages)if desc, ok := metadata.Description["en"]; ok {fmt.Printf("Description: %s\n", desc)}
Output:Database type: GeoIP2-CityBuild time: 2022-07-26 14:53:10IP version: IPv6Languages: [en zh]Description: GeoIP2 City Test Database (fake GeoIP2 data, for example purposes only)

typeReaderOption

type ReaderOption func(*readerOptions)

ReaderOption are options forOpen andOpenBytes.

This was added to allow for future options, e.g., for caching, withoutcausing a breaking API change.

typeResult

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

Result holds the result of the database lookup.

func (Result)Decode

func (rResult) Decode(vany)error

Decode unmarshals the data from the data section into the value pointed toby v. If v is nil or not a pointer, an error is returned. If the data inthe database record cannot be stored in v because of type differences, anUnmarshalTypeError is returned. If the database is invalid or otherwisecannot be read, an InvalidDatabaseError is returned.

An error will also be returned if there was an error during theReader.Lookup call.

If the Reader.Lookup call did not find a value for the IP address, no errorwill be returned and v will be unchanged.

func (Result)DecodePath

func (rResult) DecodePath(vany, path ...any)error

DecodePath unmarshals a value from data section into v, following thespecified path.

The v parameter should be a pointer to the value where the decoded datawill be stored. If v is nil or not a pointer, an error is returned. If thedata in the database record cannot be stored in v because of typedifferences, an UnmarshalTypeError is returned.

The path is a variadic list of keys (strings) and/or indices (ints) thatdescribe the nested structure to traverse in the data to reach the desiredvalue.

For maps, string path elements are used as keys.For arrays, int path elements are used as indices. A negative offset willreturn values from the end of the array, e.g., -1 will return the lastelement.

If the path is empty, the entire data structure is decoded into v.

To check if a path exists (rather than relying on zero values), decodeinto a pointer and check if it remains nil:

var city *stringerr := result.DecodePath(&city, "city", "names", "en")if err != nil {// Handle error}if city == nil {// Path not found} else {// Path exists, city contains the value}

Returns an error if:

  • the path is invalid
  • the data cannot be decoded into the type of v
  • v is not a pointer or the database record cannot be stored in v due totype mismatch
  • the Result does not contain valid data

Example usage:

var city stringerr := result.DecodePath(&city, "city", "names", "en")var geonameID interr := result.DecodePath(&geonameID, "subdivisions", 0, "geoname_id")

func (Result)Err

func (rResult) Err()error

Err provides a way to check whether there was an error during the lookupwithout calling Result.Decode. If there was an error, it will also bereturned from Result.Decode.

func (Result)Found

func (rResult) Found()bool

Found will return true if the IP was found in the search tree. It willreturn false if the IP was not found or if there was an error.

func (Result)Offset

func (rResult) Offset()uintptr

Offset returns the offset of the record in the database. This can bepassed to (*Reader).LookupOffset. It can also be used as a uniqueidentifier for the data record in the particular database to cache the datarecord across lookups. Note that while the offset uniquely identifies thedata record, other data in Result may differ between lookups. The offsetis only valid for the current database version. If you update the databasefile, you must invalidate any cache associated with the previous version.

func (Result)Prefix

func (rResult) Prefix()netip.Prefix

Prefix returns the netip.Prefix representing the network associated withthe data record in the database.

typeUnmarshalTypeError

type UnmarshalTypeError =mmdberrors.UnmarshalTypeError

UnmarshalTypeError is returned when the value in the database cannot beassigned to the specified data type.

Source Files

View all Source files

Directories

PathSynopsis
internal
decoder
Package decoder provides low-level decoding utilities for MaxMind DB data.
Package decoder provides low-level decoding utilities for MaxMind DB data.
mmdberrors
Package mmdberrors is an internal package for the errors used in this module.
Package mmdberrors is an internal package for the errors used in this module.
Package mmdbdata provides low-level types and interfaces for custom MaxMind DB decoding.
Package mmdbdata provides low-level types and interfaces for custom MaxMind DB decoding.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp