File: example_test.go

package info (click to toggle)
golang-github-oschwald-maxminddb-golang-v2 2.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,132 kB
  • sloc: perl: 557; makefile: 3
file content (348 lines) | stat: -rw-r--r-- 10,031 bytes parent folder | download | duplicates (2)
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package maxminddb_test

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

	"github.com/oschwald/maxminddb-golang/v2"
	"github.com/oschwald/maxminddb-golang/v2/mmdbdata"
)

// This example shows how to decode to a struct.
func ExampleReader_Lookup_struct() {
	db, err := maxminddb.Open("test-data/test-data/GeoIP2-City-Test.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	addr := netip.MustParseAddr("81.2.69.142")

	var record struct {
		Country struct {
			ISOCode string `maxminddb:"iso_code"`
		} `maxminddb:"country"`
	} // Or any appropriate struct

	err = db.Lookup(addr).Decode(&record)
	if err != nil {
		log.Panic(err)
	}
	fmt.Print(record.Country.ISOCode)
	// Output:
	// GB
}

// This example demonstrates how to decode to an any.
func ExampleReader_Lookup_interface() {
	db, err := maxminddb.Open("test-data/test-data/GeoIP2-City-Test.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	addr := netip.MustParseAddr("81.2.69.142")

	var record any
	err = db.Lookup(addr).Decode(&record)
	if err != nil {
		log.Panic(err)
	}
	fmt.Printf("%v", record)
	// Output:
	// map[city:map[geoname_id:2643743 names:map[de:London en:London es:Londres fr:Londres ja:ロンドン pt-BR:Londres ru:Лондон]] continent:map[code:EU geoname_id:6255148 names:map[de:Europa en:Europe es:Europa fr:Europe ja:ヨーロッパ pt-BR:Europa ru:Европа zh-CN:欧洲]] country:map[geoname_id:2635167 iso_code:GB names:map[de:Vereinigtes Königreich en:United Kingdom es:Reino Unido fr:Royaume-Uni ja:イギリス pt-BR:Reino Unido ru:Великобритания zh-CN:英国]] location:map[accuracy_radius:10 latitude:51.5142 longitude:-0.0931 time_zone:Europe/London] registered_country:map[geoname_id:6252001 iso_code:US names:map[de:USA en:United States es:Estados Unidos fr:États-Unis ja:アメリカ合衆国 pt-BR:Estados Unidos ru:США zh-CN:美国]] subdivisions:[map[geoname_id:6269131 iso_code:ENG names:map[en:England es:Inglaterra fr:Angleterre pt-BR:Inglaterra]]]]
}

// This example demonstrates how to iterate over all networks in the
// database.
func ExampleReader_Networks() {
	db, err := maxminddb.Open("test-data/test-data/GeoIP2-Connection-Type-Test.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	for result := range db.Networks() {
		record := struct {
			ConnectionType string `maxminddb:"connection_type"`
		}{}

		err := result.Decode(&record)
		if err != nil {
			log.Panic(err)
		}
		fmt.Printf("%s: %s\n", result.Prefix(), record.ConnectionType)
	}
	// Output:
	// 1.0.0.0/24: Cable/DSL
	// 1.0.1.0/24: Cellular
	// 1.0.2.0/23: Cable/DSL
	// 1.0.4.0/22: Cable/DSL
	// 1.0.8.0/21: Cable/DSL
	// 1.0.16.0/20: Cable/DSL
	// 1.0.32.0/19: Cable/DSL
	// 1.0.64.0/18: Cable/DSL
	// 1.0.128.0/17: Cable/DSL
	// 2.125.160.216/29: Cable/DSL
	// 67.43.156.0/24: Cellular
	// 80.214.0.0/20: Cellular
	// 96.1.0.0/16: Cable/DSL
	// 96.10.0.0/15: Cable/DSL
	// 96.69.0.0/16: Cable/DSL
	// 96.94.0.0/15: Cable/DSL
	// 108.96.0.0/11: Cellular
	// 149.101.100.0/28: Cellular
	// 175.16.199.0/24: Cable/DSL
	// 187.156.138.0/24: Cable/DSL
	// 201.243.200.0/24: Corporate
	// 207.179.48.0/20: Cellular
	// 216.160.83.56/29: Corporate
	// 2003::/24: Cable/DSL
}

// This example demonstrates how to validate a MaxMind DB file and access metadata.
func ExampleReader_Verify() {
	db, err := maxminddb.Open("test-data/test-data/GeoIP2-City-Test.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Verify database integrity
	if err := db.Verify(); err != nil {
		log.Printf("Database validation failed: %v", err)
		return
	}

	// Access metadata information
	metadata := db.Metadata
	fmt.Printf("Database type: %s\n", metadata.DatabaseType)
	fmt.Printf("Build time: %s\n", metadata.BuildTime().UTC().Format("2006-01-02 15:04:05"))
	fmt.Printf("IP version: IPv%d\n", metadata.IPVersion)
	fmt.Printf("Languages: %v\n", metadata.Languages)

	if desc, ok := metadata.Description["en"]; ok {
		fmt.Printf("Description: %s\n", desc)
	}

	// Output:
	// Database type: GeoIP2-City
	// Build time: 2022-07-26 14:53:10
	// IP version: IPv6
	// Languages: [en zh]
	// Description: GeoIP2 City Test Database (fake GeoIP2 data, for example purposes only)
}

// This example demonstrates how to iterate over all networks in the
// database which are contained within an arbitrary network.
func ExampleReader_NetworksWithin() {
	db, err := maxminddb.Open("test-data/test-data/GeoIP2-Connection-Type-Test.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	prefix, err := netip.ParsePrefix("1.0.0.0/8")
	if err != nil {
		log.Panic(err)
	}

	for result := range db.NetworksWithin(prefix) {
		record := struct {
			ConnectionType string `maxminddb:"connection_type"`
		}{}
		err := result.Decode(&record)
		if err != nil {
			log.Panic(err)
		}
		fmt.Printf("%s: %s\n", result.Prefix(), record.ConnectionType)
	}

	// Output:
	// 1.0.0.0/24: Cable/DSL
	// 1.0.1.0/24: Cellular
	// 1.0.2.0/23: Cable/DSL
	// 1.0.4.0/22: Cable/DSL
	// 1.0.8.0/21: Cable/DSL
	// 1.0.16.0/20: Cable/DSL
	// 1.0.32.0/19: Cable/DSL
	// 1.0.64.0/18: Cable/DSL
	// 1.0.128.0/17: Cable/DSL
}

// This example demonstrates how to use SkipEmptyValues to iterate only over
// networks that have actual data, skipping those with empty maps or arrays.
func ExampleSkipEmptyValues() {
	db, err := maxminddb.Open("test-data/test-data/GeoIP2-Anonymous-IP-Test.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Without SkipEmptyValues, you get all networks including empty ones
	fmt.Println("All networks:")
	count := 0
	for result := range db.Networks() {
		if result.Err() != nil {
			log.Panic(result.Err())
		}
		count++
		if count > 10 {
			fmt.Printf("... (%d more networks, many with empty data)\n", 529-count)
			break
		}

		var record map[string]any
		err := result.Decode(&record)
		if err != nil {
			log.Panic(err)
		}

		if len(record) == 0 {
			fmt.Printf("%s: (empty)\n", result.Prefix())
		} else {
			fmt.Printf("%s: %v\n", result.Prefix(), record)
		}
	}

	fmt.Println("\nOnly networks with data:")
	// With SkipEmptyValues, you only get networks with actual data
	for result := range db.Networks(maxminddb.SkipEmptyValues()) {
		if result.Err() != nil {
			log.Panic(result.Err())
		}

		var record map[string]any
		err := result.Decode(&record)
		if err != nil {
			log.Panic(result.Err())
		}
		fmt.Printf("%s: %v\n", result.Prefix(), record)
	}

	// Output:
	// All networks:
	// 1.0.0.0/15: (empty)
	// 1.2.0.0/16: map[is_anonymous:true is_anonymous_vpn:true]
	// 1.3.0.0/16: (empty)
	// 1.4.0.0/14: (empty)
	// 1.8.0.0/13: (empty)
	// 1.16.0.0/12: (empty)
	// 1.32.0.0/11: (empty)
	// 1.64.0.0/11: (empty)
	// 1.96.0.0/12: (empty)
	// 1.112.0.0/13: (empty)
	// ... (518 more networks, many with empty data)
	//
	// Only networks with data:
	// 1.2.0.0/16: map[is_anonymous:true is_anonymous_vpn:true]
	// 1.124.213.1/32: map[is_anonymous:true is_anonymous_vpn:true is_tor_exit_node:true]
	// 65.0.0.0/13: map[is_anonymous:true is_tor_exit_node:true]
	// 71.160.223.0/24: map[is_anonymous:true is_hosting_provider:true]
	// 81.2.69.0/24: map[is_anonymous:true is_anonymous_vpn:true is_hosting_provider:true is_public_proxy:true is_residential_proxy:true is_tor_exit_node:true]
	// 186.30.236.0/24: map[is_anonymous:true is_public_proxy:true]
	// abcd:1000::/112: map[is_anonymous:true is_public_proxy:true]
}

// CustomCity represents a simplified city record with custom unmarshaling.
// This demonstrates the Unmarshaler interface for custom decoding.
type CustomCity struct {
	Names     map[string]string
	GeoNameID uint
}

// UnmarshalMaxMindDB implements the mmdbdata.Unmarshaler interface.
// This provides custom decoding logic, similar to how json.Unmarshaler works
// with encoding/json, allowing fine-grained control over data processing.
func (c *CustomCity) UnmarshalMaxMindDB(d *mmdbdata.Decoder) error {
	mapIter, _, err := d.ReadMap()
	if err != nil {
		return err
	}
	for key, err := range mapIter {
		if err != nil {
			return err
		}

		switch string(key) {
		case "city":
			// Decode nested city structure
			cityMapIter, _, err := d.ReadMap()
			if err != nil {
				return err
			}
			for cityKey, cityErr := range cityMapIter {
				if cityErr != nil {
					return cityErr
				}
				switch string(cityKey) {
				case "names":
					// Decode nested map[string]string for localized names
					names := make(map[string]string)
					nameMapIter, _, err := d.ReadMap()
					if err != nil {
						return err
					}
					for nameKey, nameErr := range nameMapIter {
						if nameErr != nil {
							return nameErr
						}
						value, valueErr := d.ReadString()
						if valueErr != nil {
							return valueErr
						}
						names[string(nameKey)] = value
					}
					c.Names = names
				case "geoname_id":
					geoID, err := d.ReadUint32()
					if err != nil {
						return err
					}
					c.GeoNameID = uint(geoID)
				default:
					if err := d.SkipValue(); err != nil {
						return err
					}
				}
			}
		default:
			// Skip unknown fields to ensure forward compatibility
			if err := d.SkipValue(); err != nil {
				return err
			}
		}
	}
	return nil
}

// This example demonstrates how to use the Unmarshaler interface for custom decoding.
// Types implementing Unmarshaler automatically use custom decoding logic instead of
// reflection, similar to how json.Unmarshaler works with encoding/json.
func ExampleUnmarshaler() {
	db, err := maxminddb.Open("test-data/test-data/GeoIP2-City-Test.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	addr := netip.MustParseAddr("81.2.69.142")

	// CustomCity implements Unmarshaler, so it will automatically use
	// the custom UnmarshalMaxMindDB method instead of reflection
	var city CustomCity
	err = db.Lookup(addr).Decode(&city)
	if err != nil {
		log.Panic(err)
	}

	fmt.Printf("City ID: %d\n", city.GeoNameID)
	fmt.Printf("English name: %s\n", city.Names["en"])
	fmt.Printf("German name: %s\n", city.Names["de"])

	// Output:
	// City ID: 2643743
	// English name: London
	// German name: London
}