Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

geoip2-golang

> 数据库
Open source

Unofficial MaxMind GeoIP2 Reader for Go

2.3K stars0 likes0 views
WebsiteGitHub

About

Unofficial MaxMind GeoIP2 Reader for Go

GeoIP2 Reader for Go

This library reads MaxMind GeoLite2 and GeoIP2 databases.

This library is built using the Go maxminddb reader. All data for the database record is decoded using this library. Version 2.0 provides significant performance improvements with 56% fewer allocations and 34% less memory usage compared to v1. Version 2.0 also adds Network and IPAddress fields to all result structs, and includes a HasData() method to easily check if data was found. If you only need several fields, you may get superior performance by using maxminddb's Lookup directly with a result struct that only contains the required fields. (See example_test.go in the maxminddb repository for an example of this.)

Installation

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

New in v2

Version 2.0 includes several major improvements:

  • Performance: 56% fewer allocations and 34% less memory usage
  • Modern API: Uses netip.Addr instead of net.IP for better performance
  • Network Information: All result structs now include Network and IPAddress fields
  • Data Validation: New HasData() method to easily check if data was found
  • Structured Names: Replaced map[string]string with typed Names struct for better performance

Migration

See MIGRATION.md for step-by-step guidance on upgrading from v1.

Usage

See GoDoc for documentation and examples.

Example

…

Requirements

  • Go 1.26 or later
  • MaxMind GeoIP2 or GeoLite2 database files (.mmdb format)

Generated Decoders

Database model structs use decoders generated by the maxminddb-gen tool from maxminddb-golang. This is transparent to library users and improves lookup performance while preserving the decoded results.

When changing models.go, run go generate ./... and commit the updated models_maxminddb.go. The generator version is pinned in go.mod, and CI checks that generated files are current.

Getting Database Files

GeoLite2 (Free)

Download free GeoLite2 databases from MaxMind's website. Registration required.

GeoIP2 (Commercial)

Purchase GeoIP2 databases from MaxMind for enhanced accuracy and additional features.

Database Examples

This library supports all MaxMind GeoIP2 and GeoLite2 database types. Below are examples for each database type:

City Database

The City database provides the most comprehensive geolocation data, including city, subdivision, country, and precise location information.

…

Country Database

The Country database provides country-level geolocation data.

…

ASN Database

The ASN database provides Autonomous System Number and organization information.

…

Anonymous IP Database

The Anonymous IP database identifies various types of anonymous and proxy networks.

…

Anonymous Plus Database

The Anonymous Plus database extends the Anonymous IP database with additional fields for confidence scoring, provider identification, and temporal tracking.

…

Enterprise Database

The Enterprise database provides the most comprehensive data, including all City database fields plus additional enterprise features.

…

ISP Database

The ISP database provides ISP, organization, and ASN information.

…

Domain Database

The Domain database provides the second-level domain associated with an IP address.

go
package main

import (
	"fmt"
	"log"
	"net/netip"

	"github.com/oschwald/geoip2-golang/v2"
)

func main() {
	db, err := geoip2.Open("GeoIP2-Domain.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	ip, err := netip.ParseAddr("1.2.0.0")
	if err != nil {
		log.Fatal(err)
	}

	record, err := db.Domain(ip)
	if err != nil {
		log.Fatal(err)
	}

	if !record.HasData() {
		fmt.Println("No data found for this IP")
		return
	}

	fmt.Printf("Domain: %v\n", record.Domain)
	fmt.Printf("Network: %v\n", record.Network)
	fmt.Printf("IP Address: %v\n", record.IPAddress)
}

Connection Type Database

The Connection Type database identifies the connection type of an IP address.

…

Error Handling

All database lookups can return errors and should be handled appropriately:

…

Performance Tips

Database Reuse

Always reuse database instances across requests rather than opening/closing repeatedly:

go
// Good: Create once, use many times
db, err := geoip2.Open("GeoIP2-City.mmdb")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

// Use db for multiple lookups...

Memory Usage

For applications needing only specific fields, consider using the lower-level maxminddb library with custom result structs to reduce memory allocation.

Concurrent Usage

The Reader is safe for concurrent use by multiple goroutines.

JSON Serialization

All result structs include JSON tags and support marshaling to JSON:

go
record, err := db.City(ip)
if err != nil {
    log.Fatal(err)
}

jsonData, err := json.Marshal(record)
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(jsonData))

Migration from v1

Breaking Changes

  • Import Path: Change from github.com/oschwald/geoip2-golang to github.com/oschwald/geoip2-golang/v2
  • IP Type: Use netip.Addr instead of net.IP
  • Field Names: IsoCode → ISOCode
  • Names Access: Use struct fields instead of map access
  • Data Validation: Use HasData() method to check for data availability

Migration Example

go
// v1
import "github.com/oschwald/geoip2-golang"

ip := net.ParseIP("81.2.69.142")
record, err := db.City(ip)
cityName := record.City.Names["en"]

// v2
import "github.com/oschwald/geoip2-golang/v2"

ip, err := netip.ParseAddr("81.2.69.142")
if err != nil {
    // handle error
}
record, err := db.City(ip)
if !record.HasData() {
    // handle no data found
}
cityName := record.City.Names.English

Troubleshooting

Common Issues

Database not found: Ensure the .mmdb file path is correct and readable.

No data returned: Check if HasData() returns false - the IP may not be in the database or may be a private/reserved IP.

Performance issues: Ensure you're reusing the database instance rather than opening it for each lookup.

Testing

Make sure you checked out test data submodule:

bash
git submodule init
git submodule update

Execute test suite:

go test

Contributing

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

License

This is free software, licensed under the ISC license.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Godatabasegeoipgeoip2geolocation

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库