File: README.md

package info (click to toggle)
golang-github-oschwald-maxminddb-golang-v2 2.0.0~beta10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,120 kB
  • sloc: perl: 557; makefile: 3
file content (256 lines) | stat: -rw-r--r-- 6,280 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# MaxMind DB Reader for Go

[![Go Reference](https://pkg.go.dev/badge/github.com/oschwald/maxminddb-golang/v2.svg)](https://pkg.go.dev/github.com/oschwald/maxminddb-golang/v2)

This is a Go reader for the MaxMind DB format. Although this can be used to
read [GeoLite2](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data)
and [GeoIP2](https://www.maxmind.com/en/geoip2-databases) databases,
[geoip2](https://github.com/oschwald/geoip2-golang) provides a higher-level API
for doing so.

This is not an official MaxMind API.

## Installation

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

## Version 2.0 Features

Version 2.0 includes significant improvements:

- **Modern API**: Uses `netip.Addr` instead of `net.IP` for better performance
- **Custom Unmarshaling**: Implement `Unmarshaler` interface for
  zero-allocation decoding
- **Network Iteration**: Iterate over all networks in a database with
  `Networks()` and `NetworksWithin()`
- **Enhanced Performance**: Optimized data structures and decoding paths
- **Go 1.23+ Support**: Takes advantage of modern Go features including
  iterators
- **Better Error Handling**: More detailed error types and improved debugging

## Quick Start

```go
package main

import (
	"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

```go
db, err := maxminddb.Open("GeoLite2-City.mmdb")
if err != nil {
	log.Fatal(err)
}
defer db.Close()

var record any
ip := netip.MustParseAddr("1.2.3.4")
err = db.Lookup(ip).Decode(&record)
```

### Custom Struct Decoding

```go
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 City
err = db.Lookup(ip).Decode(&city)
```

### High-Performance Custom Unmarshaling

```go
type FastCity struct {
	CountryISO string
	CityName   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 data
	for 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

```go
// Iterate over all networks in the 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)
}

// Iterate over networks within a specific prefix
prefix := netip.MustParsePrefix("192.168.0.0/16")
for result := range db.NetworksWithin(prefix) {
	// Process networks within 192.168.0.0/16
}
```

### Path-Based Decoding

```go
var countryCode string
err = db.Lookup(ip).DecodePath(&countryCode, "country", "iso_code")

var cityName string
err = db.Lookup(ip).DecodePath(&cityName, "city", "names", "en")
```

## Supported Database Types

This library supports **all 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 format
  specification

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

## Performance Tips

1. **Reuse Reader instances**: The `Reader` is thread-safe and should be reused
   across goroutines
2. **Use specific structs**: Only decode the fields you need rather than using
   `any`
3. **Implement Unmarshaler**: For high-throughput applications, implement
   custom unmarshaling
4. **Consider caching**: Use `Result.Offset()` as a cache key for database
   records

## Getting Database Files

### Free GeoLite2 Databases

Download from
[MaxMind's GeoLite page](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data).

## Documentation

- [Go Reference](https://pkg.go.dev/github.com/oschwald/maxminddb-golang/v2)
- [MaxMind DB File Format Specification](https://maxmind.github.io/MaxMind-DB/)

## Requirements

- Go 1.23 or later
- MaxMind DB file in .mmdb format

## 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.