country-geo-locations/pkg/geoloc/database.go

66 lines
1.1 KiB
Go
Raw Normal View History

2023-12-19 13:56:03 +01:00
package geoloc
import (
"fmt"
"github.com/hashicorp/go-memdb"
)
var database *memdb.MemDB
func CreateDatabase(ipinfos []IPInfo) (err error) {
2023-12-19 13:56:03 +01:00
schema := &memdb.DBSchema{
Tables: map[string]*memdb.TableSchema{
"ipinfo": {
Name: "ipinfo",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.UintFieldIndex{Field: "IPNumFrom"},
},
},
},
},
}
database, err = memdb.NewMemDB(schema)
2023-12-19 13:56:03 +01:00
if err != nil {
return
2023-12-19 13:56:03 +01:00
}
txn := database.Txn(true)
2023-12-19 13:56:03 +01:00
defer txn.Abort()
for _, ipinfo := range ipinfos {
if err = txn.Insert("ipinfo", ipinfo); err != nil {
return
2023-12-19 13:56:03 +01:00
}
}
txn.Commit()
return
2023-12-19 13:56:03 +01:00
}
func SearchIPNet(ipnetnum uint) (*IPInfo, error) {
txn := database.Txn(false)
defer txn.Abort()
var ipinfo IPInfo
for {
raw, err := txn.First("ipinfo", "id", ipnetnum)
if err != nil {
return nil, err
}
if raw != nil {
ipinfo = raw.(IPInfo)
break
}
if ipnetnum == 0 {
return nil, fmt.Errorf("SearchIPNet: IP net not found")
}
ipnetnum = ipnetnum - 256
}
return &ipinfo, nil
}