github.com/aaabigfish/gopkg@v1.1.0/net/ip2region/ip2region.go (about)

     1  package ip2region
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/aaabigfish/gopkg/net/ip"
     7  
     8  	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
     9  )
    10  
    11  type IpInfo struct {
    12  	Country   string
    13  	CountryId int64
    14  	Region    string
    15  	Province  string
    16  	City      string
    17  	ISP       string
    18  }
    19  
    20  type Ip2Region struct {
    21  	region *xdb.Searcher
    22  }
    23  
    24  func New(path string) (*Ip2Region, error) {
    25  	// 1、从 dbPath 加载整个 xdb 到内存
    26  	cBuff, err := xdb.LoadContentFromFile(path)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  
    31  	// 2、用全局的 cBuff 创建完全基于内存的查询对象。
    32  	searcher, err := xdb.NewWithBuffer(cBuff)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	return &Ip2Region{region: searcher}, nil
    38  }
    39  
    40  func ParseIpInfo(regionStr string) *IpInfo {
    41  	lineSlice := strings.Split(regionStr, "|")
    42  	ipInfo := IpInfo{}
    43  	length := len(lineSlice)
    44  	if length < 5 {
    45  		for i := 0; i <= 5-length; i++ {
    46  			lineSlice = append(lineSlice, "")
    47  		}
    48  	}
    49  
    50  	ipInfo.Country = lineSlice[0]
    51  	ipInfo.Region = lineSlice[1]
    52  	ipInfo.Province = lineSlice[2]
    53  	ipInfo.City = lineSlice[3]
    54  	ipInfo.ISP = lineSlice[4]
    55  
    56  	country := ipInfo.Country
    57  	if ipInfo.Country == "中国" {
    58  		if ipInfo.Province == "香港" || ipInfo.Province == "台湾省" || ipInfo.Province == "澳门" {
    59  			if ipInfo.Province == "台湾省" {
    60  				ipInfo.Province = "台湾"
    61  			}
    62  			country = ipInfo.Province
    63  		}
    64  	}
    65  
    66  	if id, ok := ip.Country[country]; ok {
    67  		ipInfo.CountryId = id
    68  	}
    69  
    70  	return &ipInfo
    71  }
    72  
    73  func (s *Ip2Region) GetIpInfo(ipStr string) (*IpInfo, error) {
    74  	regionStr, err := s.region.SearchByStr(ipStr)
    75  	if err != nil {
    76  		return nil, err
    77  	}
    78  
    79  	return ParseIpInfo(regionStr), nil
    80  }