pkg/geoloc/database.go: optimize database functions & resolve nil pointer dereference
This commit is contained in:
parent
82e8d3ca45
commit
177f378715
1 changed files with 7 additions and 17 deletions
|
@ -8,7 +8,7 @@ import (
|
||||||
|
|
||||||
var database *memdb.MemDB
|
var database *memdb.MemDB
|
||||||
|
|
||||||
func CreateDatabase(ipinfos []IPInfo) error {
|
func CreateDatabase(ipinfos []IPInfo) (err error) {
|
||||||
schema := &memdb.DBSchema{
|
schema := &memdb.DBSchema{
|
||||||
Tables: map[string]*memdb.TableSchema{
|
Tables: map[string]*memdb.TableSchema{
|
||||||
"ipinfo": {
|
"ipinfo": {
|
||||||
|
@ -24,38 +24,28 @@ func CreateDatabase(ipinfos []IPInfo) error {
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
db, err := memdb.NewMemDB(schema)
|
database, err = memdb.NewMemDB(schema)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
txn := db.Txn(true)
|
txn := database.Txn(true)
|
||||||
defer txn.Abort()
|
defer txn.Abort()
|
||||||
|
|
||||||
for _, ipinfo := range ipinfos {
|
for _, ipinfo := range ipinfos {
|
||||||
if err := txn.Insert("ipinfo", ipinfo); err != nil {
|
if err = txn.Insert("ipinfo", ipinfo); err != nil {
|
||||||
return err
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
txn.Commit()
|
txn.Commit()
|
||||||
|
return
|
||||||
database = db
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func SearchIPNet(ipnetnum uint) (*IPInfo, error) {
|
func SearchIPNet(ipnetnum uint) (*IPInfo, error) {
|
||||||
txn := database.Txn(false)
|
txn := database.Txn(false)
|
||||||
defer txn.Abort()
|
defer txn.Abort()
|
||||||
|
|
||||||
raw, err := txn.First("ipinfo", "id", ipnetnum)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if raw == nil {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var ipinfo IPInfo
|
var ipinfo IPInfo
|
||||||
for {
|
for {
|
||||||
raw, err := txn.First("ipinfo", "id", ipnetnum)
|
raw, err := txn.First("ipinfo", "id", ipnetnum)
|
||||||
|
|
Loading…
Add table
Reference in a new issue