44 lines
1.1 KiB
Go
44 lines
1.1 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
|
||
|
"github.com/lionsoul2014/ip2region/binding/golang/xdb"
|
||
|
)
|
||
|
|
||
|
func ip2region(ip string) (string, error) {
|
||
|
var dbPath = "ip2region/ip2region.xdb"
|
||
|
searcher, err := xdb.NewWithFileOnly(dbPath)
|
||
|
if err != nil {
|
||
|
fmt.Printf("failed to create searcher: %s\n", err.Error())
|
||
|
}
|
||
|
|
||
|
defer searcher.Close()
|
||
|
|
||
|
// 备注:并发使用,每个 goroutine 需要创建一个独立的 searcher 对象。
|
||
|
|
||
|
// 1、从 dbPath 加载整个 xdb 到内存
|
||
|
cBuff, err := xdb.LoadContentFromFile(dbPath)
|
||
|
if err != nil {
|
||
|
fmt.Printf("failed to load content from `%s`: %s\n", dbPath, err)
|
||
|
}
|
||
|
|
||
|
// 2、用全局的 cBuff 创建完全基于内存的查询对象。
|
||
|
searcher, err = xdb.NewWithBuffer(cBuff)
|
||
|
if err != nil {
|
||
|
fmt.Printf("failed to create searcher with content: %s\n", err)
|
||
|
}
|
||
|
|
||
|
region, err := searcher.SearchByStr(ip)
|
||
|
if err != nil {
|
||
|
fmt.Printf("failed to SearchIP(%s): %s\n", ip, err)
|
||
|
}
|
||
|
|
||
|
//tStart := time.Time{}
|
||
|
//fmt.Printf("{region: %s, took: %s}\n", region, time.Since(tStart))
|
||
|
|
||
|
// 备注:并发使用,用整个 xdb 缓存创建的 searcher 对象可以安全用于并发。
|
||
|
|
||
|
return region, err
|
||
|
}
|