Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

MaxMind DB Reader for Go

License

NotificationsYou must be signed in to change notification settings

oschwald/maxminddb-golang

Repository files navigation

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")funcmain() {db,err:=maxminddb.Open("GeoLite2-City.mmdb")iferr!=nil {log.Fatal(err)}deferdb.Close()ip,err:=netip.ParseAddr("81.2.69.142")iferr!=nil {log.Fatal(err)}varrecordstruct {Countrystruct {ISOCodestring`maxminddb:"iso_code"`Namesmap[string]string`maxminddb:"names"`}`maxminddb:"country"`Citystruct {Namesmap[string]string`maxminddb:"names"`}`maxminddb:"city"`}err=db.Lookup(ip).Decode(&record)iferr!=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")iferr!=nil {log.Fatal(err)}deferdb.Close()varrecordanyip:=netip.MustParseAddr("1.2.3.4")err=db.Lookup(ip).Decode(&record)

Custom Struct Decoding

typeCitystruct {Countrystruct {ISOCodestring`maxminddb:"iso_code"`Namesstruct {Englishstring`maxminddb:"en"`Germanstring`maxminddb:"de"`}`maxminddb:"names"`}`maxminddb:"country"`}varcityCityerr=db.Lookup(ip).Decode(&city)

High-Performance Custom Unmarshaling

typeFastCitystruct {CountryISOstringCityNamestring}func (c*FastCity)UnmarshalMaxMindDB(d*maxminddb.Decoder)error {mapIter,size,err:=d.ReadMap()iferr!=nil {returnerr}// Pre-allocate with correct capacity for better performance_=size// Use for pre-allocation if storing map dataforkey,err:=rangemapIter {iferr!=nil {returnerr}switchstring(key) {case"country":countryIter,_,err:=d.ReadMap()iferr!=nil {returnerr}forcountryKey,countryErr:=rangecountryIter {ifcountryErr!=nil {returncountryErr}ifstring(countryKey)=="iso_code" {c.CountryISO,err=d.ReadString()iferr!=nil {returnerr}}else {iferr:=d.SkipValue();err!=nil {returnerr}}}default:iferr:=d.SkipValue();err!=nil {returnerr}}}returnnil}

Network Iteration

// Iterate over all networks in the databaseforresult:=rangedb.Networks() {varrecordstruct {Countrystruct {ISOCodestring`maxminddb:"iso_code"`}`maxminddb:"country"`}err:=result.Decode(&record)iferr!=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")forresult:=rangedb.NetworksWithin(prefix) {// Process networks within 192.168.0.0/16}

Path-Based Decoding

varcountryCodestringerr=db.Lookup(ip).DecodePath(&countryCode,"country","iso_code")varcityNamestringerr=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.


[8]ページ先頭

©2009-2025 Movatter.jp