- Notifications
You must be signed in to change notification settings - Fork104
oschwald/maxminddb-golang
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
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.
go get github.com/oschwald/maxminddb-golang/v2
Version 2.0 includes significant improvements:
- Modern API: Uses
netip.Addrinstead ofnet.IPfor better performance - Custom Unmarshaling: Implement
Unmarshalerinterface forzero-allocation decoding - Network Iteration: Iterate over all networks in a database with
Networks()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 with
Reader.Verify()and accessmetadata helpers such asMetadata.BuildTime()
SeeMIGRATION.md for guidance on updating existing v1 code.
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"])}
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)
typeCitystruct {Countrystruct {ISOCodestring`maxminddb:"iso_code"`Namesstruct {Englishstring`maxminddb:"en"`Germanstring`maxminddb:"de"`}`maxminddb:"names"`}`maxminddb:"country"`}varcityCityerr=db.Lookup(ip).Decode(&city)
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}
// 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}
varcountryCodestringerr=db.Lookup(ip).DecodePath(&countryCode,"country","iso_code")varcityNamestringerr=db.Lookup(ip).DecodePath(&cityName,"city","names","en")
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.
- Reuse Reader instances: The
Readeris thread-safe and should be reusedacross goroutines - Use specific structs: Only decode the fields you need rather than using
any - Implement Unmarshaler: For high-throughput applications, implementcustom unmarshaling
- Consider caching: Use
Result.Offset()as a cache key for databaserecords
Download fromMaxMind's GeoLite page.
- Go 1.24 or later
- MaxMind DB file in .mmdb format
Contributions welcome! Please fork the repository and open a pull request withyour changes.
This is free software, licensed under the ISC License.
About
MaxMind DB Reader for Go
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.