github.com/nxtrace/NTrace-core@v1.3.1-0.20240513132635-39169291e8c9/ipgeo/ip2region.go (about)

     1  package ipgeo
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  	"os"
     9  	"time"
    10  
    11  	"github.com/lionsoul2014/ip2region/v1.0/binding/golang/ip2region"
    12  )
    13  
    14  const (
    15  	ipDataBasePath = "./ip2region.db"
    16  	defaultDownURL = "1"
    17  	originURL      = "https://mirror.ghproxy.com/?q=https://github.com/bqf9979/ip2region/blob/master/data/ip2region.db?raw=true"
    18  )
    19  
    20  func downloadDataBase() error {
    21  	fmt.Println("Downloading DataBase...")
    22  	resp, err := http.Get(originURL)
    23  	if err != nil {
    24  		return err
    25  	}
    26  	defer func(Body io.ReadCloser) {
    27  		err := Body.Close()
    28  		if err != nil {
    29  			panic(err)
    30  		}
    31  	}(resp.Body)
    32  
    33  	// Create the file
    34  	out, err := os.Create(ipDataBasePath)
    35  	if err != nil {
    36  		return err
    37  	}
    38  	defer func(out *os.File) {
    39  		err := out.Close()
    40  		if err != nil {
    41  			panic(err)
    42  		}
    43  	}(out)
    44  
    45  	// Write the body to file
    46  	_, err = io.Copy(out, resp.Body)
    47  	return err
    48  }
    49  
    50  func IP2Region(ip string, _ time.Duration, _ string, _ bool) (*IPGeoData, error) {
    51  	if _, err := os.Stat(ipDataBasePath); os.IsNotExist(err) {
    52  		if err = downloadDataBase(); err != nil {
    53  			panic("Download Failed!")
    54  		}
    55  	}
    56  	region, err := ip2region.New(ipDataBasePath)
    57  	if err != nil {
    58  		panic("Cannot find ip2region.db")
    59  	}
    60  	defer region.Close()
    61  	info, searchErr := region.MemorySearch(ip)
    62  	if searchErr != nil {
    63  		return &IPGeoData{}, errors.New("no results")
    64  	}
    65  
    66  	if info.Country == "0" {
    67  		info.Country = ""
    68  	}
    69  
    70  	if info.Province == "0" {
    71  		info.Province = ""
    72  	}
    73  
    74  	if info.City == "0" {
    75  		info.City = ""
    76  	}
    77  
    78  	if info.ISP == "0" {
    79  		info.ISP = ""
    80  	}
    81  
    82  	return &IPGeoData{
    83  		Owner:   info.ISP,
    84  		Country: info.Country,
    85  		Prov:    info.Province,
    86  		City:    info.City,
    87  	}, nil
    88  }