2023-12-19 13:56:03 +01:00
|
|
|
package geoloc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/hashicorp/go-memdb"
|
|
|
|
)
|
|
|
|
|
|
|
|
var database *memdb.MemDB
|
|
|
|
|
2024-02-26 09:39:45 +01:00
|
|
|
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"},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2024-02-26 09:39:45 +01:00
|
|
|
database, err = memdb.NewMemDB(schema)
|
2023-12-19 13:56:03 +01:00
|
|
|
if err != nil {
|
2024-02-26 09:39:45 +01:00
|
|
|
return
|
2023-12-19 13:56:03 +01:00
|
|
|
}
|
|
|
|
|
2024-02-26 09:39:45 +01:00
|
|
|
txn := database.Txn(true)
|
2023-12-19 13:56:03 +01:00
|
|
|
defer txn.Abort()
|
|
|
|
|
|
|
|
for _, ipinfo := range ipinfos {
|
2024-02-26 09:39:45 +01:00
|
|
|
if err = txn.Insert("ipinfo", ipinfo); err != nil {
|
|
|
|
return
|
2023-12-19 13:56:03 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
txn.Commit()
|
2024-02-26 09:39:45 +01:00
|
|
|
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
|
|
|
|
}
|