oschwald/geoip2-golang
حول
قارئ غير رسمي لـ MaxMind GeoIP2 بلغة Go.
البيانات والتحليلاتالنمو المقاس للنجوم
- خلال 24 ساعة
- ٠
- خلال 7 أيام
- +٢
- خلال 15 يومًا
- +١
- خلال شهر
- +٢
تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.
README.md
الأصل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.Addrinstead ofnet.IPfor better performance - Network Information: All result structs now include
NetworkandIPAddressfields - Data Validation: New
HasData()method to easily check if data was found - Structured Names: Replaced
map[string]stringwith typedNamesstruct for better performance
Migration
See MIGRATION.md for step-by-step guidance on upgrading from v1.
Usage
See GoDoc for documentation and examples.
Example
package main
import (
"fmt"
"log"
"net/netip"
"github.com/oschwald/geoip2-golang/v2"
)
func main() {
db, err := geoip2.Open("GeoIP2-City.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// If you are using strings that may be invalid, use netip.ParseAddr and check for errors
ip, err := netip.ParseAddr("81.2.69.142")
if err != nil {
log.Fatal(err)
}
record, err := db.City(ip)
if err != nil {
log.Fatal(err)
}
if !record.HasData() {
fmt.Println("No data found for this IP")
return
}
fmt.Printf("Portuguese (BR) city name: %v\n", record.City.Names.BrazilianPortuguese)
if len(record.Subdivisions) > 0 {
fmt.Printf("English subdivision name: %v\n", record.Subdivisions[0].Names.English)
}
fmt.Printf("Russian country name: %v\n", record.Country.Names.Russian)
fmt.Printf("ISO country code: %v\n", record.Country.ISOCode)
fmt.Printf("Time zone: %v\n", record.Location.TimeZone)
if record.Location.HasCoordinates() {
fmt.Printf("Coordinates: %v, %v\n", *record.Location.Latitude, *record.Location.Longitude)
}
// Output:
// Portuguese (BR) city name: Londres
// English subdivision name: England
// Russian country name: Великобритания
// ISO country code: GB
// Time zone: Europe/London
// Coordinates: 51.5142, -0.0931
}
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 the database types used by the lookup methods below, not
every MaxMind database type. Open and OpenBytes return
UnknownDatabaseTypeError for unsupported types.
City Database
The City database provides the most comprehensive geolocation data, including city, subdivision, country, and precise location information.
package main
import (
"fmt"
"log"
"net/netip"
"github.com/oschwald/geoip2-golang/v2"
)
func main() {
db, err := geoip2.Open("GeoIP2-City.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ip, err := netip.ParseAddr("128.101.101.101")
if err != nil {
log.Fatal(err)
}
record, err := db.City(ip)
if err != nil {
log.Fatal(err)
}
if !record.HasData() {
fmt.Println("No data found for this IP")
return
}
fmt.Printf("City: %v\n", record.City.Names.English)
if len(record.Subdivisions) > 0 {
fmt.Printf("Subdivision: %v\n", record.Subdivisions[0].Names.English)
}
fmt.Printf("Country: %v (%v)\n", record.Country.Names.English, record.Country.ISOCode)
fmt.Printf("Continent: %v (%v)\n", record.Continent.Names.English, record.Continent.Code)
fmt.Printf("Postal Code: %v\n", record.Postal.Code)
if record.Location.HasCoordinates() {
fmt.Printf("Location: %v, %v\n", *record.Location.Latitude, *record.Location.Longitude)
}
fmt.Printf("Time Zone: %v\n", record.Location.TimeZone)
fmt.Printf("Network: %v\n", record.Traits.Network)
fmt.Printf("IP Address: %v\n", record.Traits.IPAddress)
}
Country Database
The Country database provides country-level geolocation data.
package main
import (
"fmt"
"log"
"net/netip"
"github.com/oschwald/geoip2-golang/v2"
)
func main() {
db, err := geoip2.Open("GeoIP2-Country.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ip, err := netip.ParseAddr("81.2.69.142")
if err != nil {
log.Fatal(err)
}
record, err := db.Country(ip)
if err != nil {
log.Fatal(err)
}
if !record.HasData() {
fmt.Println("No data found for this IP")
return
}
fmt.Printf("Country: %v (%v)\n", record.Country.Names.English, record.Country.ISOCode)
fmt.Printf("Continent: %v (%v)\n", record.Continent.Names.English, record.Continent.Code)
fmt.Printf("Is in EU: %v\n", record.Country.IsInEuropeanUnion)
fmt.Printf("Network: %v\n", record.Traits.Network)
fmt.Printf("IP Address: %v\n", record.Traits.IPAddress)
if record.RegisteredCountry.Names.English != "" {
fmt.Printf("Registered Country: %v (%v)\n",
record.RegisteredCountry.Names.English, record.RegisteredCountry.ISOCode)
}
}
ASN Database
The ASN database provides Autonomous System Number and organization information.
package main
import (
"fmt"
"log"
"net/netip"
"github.com/oschwald/geoip2-golang/v2"
)
func main() {
db, err := geoip2.Open("GeoLite2-ASN.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ip, err := netip.ParseAddr("1.128.0.0")
if err != nil {
log.Fatal(err)
}
record, err := db.ASN(ip)
if err != nil {
log.Fatal(err)
}
if !record.HasData() {
fmt.Println("No data found for this IP")
return
}
fmt.Printf("ASN: %v\n", record.AutonomousSystemNumber)
fmt.Printf("Organization: %v\n", record.AutonomousSystemOrganization)
fmt.Printf("Network: %v\n", record.Network)
fmt.Printf("IP Address: %v\n", record.IPAddress)
}
Anonymous IP Database
The Anonymous IP database identifies various types of anonymous and proxy networks.
package main
import (
"fmt"
"log"
"net/netip"
"github.com/oschwald/geoip2-golang/v2"
)
func main() {
db, err := geoip2.Open("GeoIP2-Anonymous-IP.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ip, err := netip.ParseAddr("81.2.69.142")
if err != nil {
log.Fatal(err)
}
record, err := db.AnonymousIP(ip)
if err != nil {
log.Fatal(err)
}
if !record.HasData() {
fmt.Println("No data found for this IP")
return
}
fmt.Printf("Is Anonymous: %v\n", record.IsAnonymous)
fmt.Printf("Is Anonymous VPN: %v\n", record.IsAnonymousVPN)
fmt.Printf("Is Hosting Provider: %v\n", record.IsHostingProvider)
fmt.Printf("Is Public Proxy: %v\n", record.IsPublicProxy)
fmt.Printf("Is Residential Proxy: %v\n", record.IsResidentialProxy)
fmt.Printf("Is Tor Exit Node: %v\n", record.IsTorExitNode)
fmt.Printf("Network: %v\n", record.Network)
fmt.Printf("IP Address: %v\n", record.IPAddress)
}
Anonymous Plus Database
The Anonymous Plus database extends the Anonymous IP database with additional fields for confidence scoring, provider identification, and temporal tracking.
package main
import (
"fmt"
"log"
"net/netip"
"github.com/oschwald/geoip2-golang/v2"
)
func main() {
db, err := geoip2.Open("GeoIP-Anonymous-Plus.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ip, err := netip.ParseAddr("1.2.0.1")
if err != nil {
log.Fatal(err)
}
record, err := db.AnonymousPlus(ip)
if err != nil {
log.Fatal(err)
}
if !record.HasData() {
fmt.Println("No data found for this IP")
return
}
// Standard anonymous IP flags
fmt.Printf("Is Anonymous: %v\n", record.IsAnonymous)
fmt.Printf("Is Anonymous VPN: %v\n", record.IsAnonymousVPN)
fmt.Printf("Is Hosting Provider: %v\n", record.IsHostingProvider)
fmt.Printf("Is Public Proxy: %v\n", record.IsPublicProxy)
fmt.Printf("Is Residential Proxy: %v\n", record.IsResidentialProxy)
fmt.Printf("Is Tor Exit Node: %v\n", record.IsTorExitNode)
// Anonymous Plus specific fields
fmt.Printf("Anonymizer Confidence: %v\n", record.AnonymizerConfidence)
fmt.Printf("Provider Name: %v\n", record.ProviderName)
if !record.NetworkLastSeen.IsZero() {
fmt.Printf("Network Last Seen: %v\n", record.NetworkLastSeen.Format("2006-01-02"))
}
fmt.Printf("Network: %v\n", record.Network)
fmt.Printf("IP Address: %v\n", record.IPAddress)
}
Enterprise Database
The Enterprise database provides the most comprehensive data, including all City database fields plus additional enterprise features.
package main
import (
"fmt"
"log"
"net/netip"
"github.com/oschwald/geoip2-golang/v2"
)
func main() {
db, err := geoip2.Open("GeoIP2-Enterprise.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ip, err := netip.ParseAddr("128.101.101.101")
if err != nil {
log.Fatal(err)
}
record, err := db.Enterprise(ip)
if err != nil {
log.Fatal(err)
}
if !record.HasData() {
fmt.Println("No data found for this IP")
return
}
// Basic location information
fmt.Printf("City: %v\n", record.City.Names.English)
fmt.Printf("Country: %v (%v)\n", record.Country.Names.English, record.Country.ISOCode)
if record.Location.HasCoordinates() {
fmt.Printf("Location: %v, %v\n", *record.Location.Latitude, *record.Location.Longitude)
}
// Enterprise-specific fields
fmt.Printf("ISP: %v\n", record.Traits.ISP)
fmt.Printf("Organization: %v\n", record.Traits.Organization)
fmt.Printf("ASN: %v (%v)\n", record.Traits.AutonomousSystemNumber,
record.Traits.AutonomousSystemOrganization)
fmt.Printf("Connection Type: %v\n", record.Traits.ConnectionType)
fmt.Printf("Domain: %v\n", record.Traits.Domain)
fmt.Printf("User Type: %v\n", record.Traits.UserType)
fmt.Printf("Is Anycast: %v\n", record.Traits.IsAnycast)
// Mobile carrier information (if available)
if record.Traits.MobileCountryCode != "" {
fmt.Printf("Mobile Country Code: %v\n", record.Traits.MobileCountryCode)
fmt.Printf("Mobile Network Code: %v\n", record.Traits.MobileNetworkCode)
}
fmt.Printf("Network: %v\n", record.Traits.Network)
fmt.Printf("IP Address: %v\n", record.Traits.IPAddress)
}
ISP Database
The ISP database provides ISP, organization, and ASN information.
package main
import (
"fmt"
"log"
"net/netip"
"github.com/oschwald/geoip2-golang/v2"
)
func main() {
db, err := geoip2.Open("GeoIP2-ISP.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ip, err := netip.ParseAddr("1.128.0.0")
if err != nil {
log.Fatal(err)
}
record, err := db.ISP(ip)
if err != nil {
log.Fatal(err)
}
if !record.HasData() {
fmt.Println("No data found for this IP")
return
}
fmt.Printf("ISP: %v\n", record.ISP)
fmt.Printf("Organization: %v\n", record.Organization)
fmt.Printf("ASN: %v (%v)\n", record.AutonomousSystemNumber,
record.AutonomousSystemOrganization)
// Mobile carrier information (if available)
if record.MobileCountryCode != "" {
fmt.Printf("Mobile Country Code: %v\n", record.MobileCountryCode)
fmt.Printf("Mobile Network Code: %v\n", record.MobileNetworkCode)
}
fmt.Printf("Network: %v\n", record.Network)
fmt.Printf("IP Address: %v\n", record.IPAddress)
}
Domain Database
The Domain database provides the second-level domain associated with an IP address.
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.
package main
import (
"fmt"
"log"
"net/netip"
"github.com/oschwald/geoip2-golang/v2"
)
func main() {
db, err := geoip2.Open("GeoIP2-Connection-Type.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ip, err := netip.ParseAddr("1.0.128.0")
if err != nil {
log.Fatal(err)
}
record, err := db.ConnectionType(ip)
if err != nil {
log.Fatal(err)
}
if !record.HasData() {
fmt.Println("No data found for this IP")
return
}
fmt.Printf("Connection Type: %v\n", record.ConnectionType)
fmt.Printf("Network: %v\n", record.Network)
fmt.Printf("IP Address: %v\n", record.IPAddress)
}
Error Handling
All database lookups can return errors and should be handled appropriately:
package main
import (
"fmt"
"log"
"net/netip"
"github.com/oschwald/geoip2-golang/v2"
)
func main() {
db, err := geoip2.Open("GeoIP2-City.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ip, err := netip.ParseAddr("10.0.0.1") // Private IP
if err != nil {
log.Fatal(err)
}
record, err := db.City(ip)
if err != nil {
log.Fatal(err)
}
// Always check if data was found
if !record.HasData() {
fmt.Println("No data found for this IP address")
return
}
// Check individual fields before using them
if record.City.Names.English != "" {
fmt.Printf("City: %v\n", record.City.Names.English)
} else {
fmt.Println("City name not available")
}
// Check array bounds for subdivisions
if len(record.Subdivisions) > 0 {
fmt.Printf("Subdivision: %v\n", record.Subdivisions[0].Names.English)
} else {
fmt.Println("No subdivision data available")
}
fmt.Printf("Country: %v\n", record.Country.Names.English)
}
Performance Tips
Database Reuse
Always reuse database instances across requests rather than opening/closing repeatedly:
// 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...
If other goroutines use db, make sure all their calls on it have returned
before Close runs. See Concurrent Usage.
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 lookup methods (City, Country, ASN, and the others) and Metadata
are safe to call concurrently from multiple goroutines.
Close is the exception. It must not run while another goroutine is calling any
method on the same Reader, including another call to Close. Close unmaps
the file when it was memory-mapped and clears the Reader's internal state, so
a lookup that is still running can read invalid memory, race with Close, or
crash the program. This applies however the Reader was opened, including with
OpenBytes. Close does not modify or free a slice you passed to OpenBytes.
Wait for all lookups on a Reader to return before you call Close on it. A
lookup that your synchronization orders after Close has returned, for example
through the same lock, is safe and returns an error. Lookup results are decoded
into new memory that does not reference the database, so they remain valid after
Close.
If you replace the Reader while your program runs, for example when a new
database file arrives, close the old Reader only after every call that may
still be using it, including Metadata, has returned. One way to do this is a
sync.RWMutex: hold the read lock while you load the current Reader and call
any method on it, and hold the write lock while you swap in the new Reader and
close the old one. Alternatively, do not call Close on the old Reader. Once
nothing references it, the garbage collector may unmap a file that Open
memory-mapped, but Go does not guarantee when or whether that happens. Until
then the old mapping stays in memory, and on Windows the old file cannot be
deleted or replaced. Calling Close unmaps it right away.
Do not overwrite the database file in place while a Reader has it open.
Write the new database to a new path and open it from there. On Unix-like
systems you can also rename the new file over the old path; Windows does not
allow replacing a file that is still memory-mapped.
JSON Serialization
All result structs include JSON tags and support marshaling to JSON:
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))
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:
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.
استكشف مشاريع مشابهة ومرتبطة
جارٍ التحميل…