Skip to content

Commit 4a8ef44

Browse files
committed
Modified DB reader interface
1 parent 7765528 commit 4a8ef44

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/ip2location/ip2proxy-go
2+
3+
go 1.14

ip2proxy.go

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,19 @@ import (
88
"bytes"
99
"encoding/binary"
1010
"fmt"
11+
"io"
1112
"math"
1213
"math/big"
1314
"net"
1415
"os"
1516
"strconv"
1617
)
1718

19+
type DBReader interface {
20+
io.ReadCloser
21+
io.ReaderAt
22+
}
23+
1824
type ip2proxymeta struct {
1925
databasetype uint8
2026
databasecolumn uint8
@@ -50,7 +56,7 @@ type IP2Proxyrecord struct {
5056
}
5157

5258
type DB struct {
53-
f *os.File
59+
f DBReader
5460
meta ip2proxymeta
5561

5662
country_position_offset uint32
@@ -94,7 +100,7 @@ var as_position = [11]uint8{0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10}
94100
var lastseen_position = [11]uint8{0, 0, 0, 0, 0, 0, 0, 0, 11, 11, 11}
95101
var threat_position = [11]uint8{0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12}
96102

97-
const module_version string = "3.0.0"
103+
const module_version string = "3.1.0"
98104

99105
var max_ipv4_range = big.NewInt(4294967295)
100106
var max_ipv6_range = big.NewInt(0)
@@ -290,6 +296,17 @@ func fatal(db *DB, err error) (*DB, error) {
290296
// OpenDB takes the path to the IP2Proxy BIN database file. It will read all the metadata required to
291297
// be able to extract the embedded proxy data, and return the underlining DB object.
292298
func OpenDB(dbpath string) (*DB, error) {
299+
f, err := os.Open(dbpath)
300+
if err != nil {
301+
return nil, err
302+
}
303+
304+
return OpenDBWithReader(f)
305+
}
306+
307+
// OpenDBWithReader takes a DBReader to the IP2Proxy BIN database file. It will read all the metadata required to
308+
// be able to extract the embedded proxy data, and return the underlining DB object.
309+
func OpenDBWithReader(reader DBReader) (*DB, error) {
293310
var db = &DB{}
294311

295312
max_ipv6_range.SetString("340282366920938463463374607431768211455", 10)
@@ -298,12 +315,9 @@ func OpenDB(dbpath string) (*DB, error) {
298315
from_teredo.SetString("42540488161975842760550356425300246528", 10)
299316
to_teredo.SetString("42540488241204005274814694018844196863", 10)
300317

301-
var err error
302-
db.f, err = os.Open(dbpath)
303-
if err != nil {
304-
return nil, err
305-
}
318+
db.f = reader
306319

320+
var err error
307321
db.meta.databasetype, err = db.readuint8(1)
308322
if err != nil {
309323
return fatal(db, err)

0 commit comments

Comments
 (0)