pkg/geoloc/database.go: optimize database functions & resolve nil pointer dereference

This commit is contained in:
Tom Neuber 2024-02-26 09:39:45 +01:00
parent 82e8d3ca45
commit 177f378715

View file

@ -8,7 +8,7 @@ import (
var database *memdb.MemDB
func CreateDatabase(ipinfos []IPInfo) error {
func CreateDatabase(ipinfos []IPInfo) (err error) {
schema := &memdb.DBSchema{
Tables: map[string]*memdb.TableSchema{
"ipinfo": {
@ -24,38 +24,28 @@ func CreateDatabase(ipinfos []IPInfo) error {
},
}
db, err := memdb.NewMemDB(schema)
database, err = memdb.NewMemDB(schema)
if err != nil {
return err
return
}
txn := db.Txn(true)
txn := database.Txn(true)
defer txn.Abort()
for _, ipinfo := range ipinfos {
if err := txn.Insert("ipinfo", ipinfo); err != nil {
return err
if err = txn.Insert("ipinfo", ipinfo); err != nil {
return
}
}
txn.Commit()
database = db
return nil
return
}
func SearchIPNet(ipnetnum uint) (*IPInfo, error) {
txn := database.Txn(false)
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
for {
raw, err := txn.First("ipinfo", "id", ipnetnum)