74 lines
1.7 KiB
Go
74 lines
1.7 KiB
Go
package modules
|
|
|
|
import (
|
|
"database/sql"
|
|
"log"
|
|
)
|
|
|
|
type IpInformation struct {
|
|
Ip string `json:"ip"`
|
|
CountryIsoCode string `json:"Country_Iso_Code"`
|
|
CountryName string `json:"Country_Name"`
|
|
City string `json:"City"`
|
|
TimeZone string `json:"Time_Zone"`
|
|
}
|
|
|
|
func MysqlQuery(ip string) IpInformation {
|
|
// 连接到MySQL数据库
|
|
db, err := sql.Open("mysql", "root:990821@tcp(192.168.2.20:3306)/checkip")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer db.Close()
|
|
|
|
// 执行查询语句
|
|
query := `
|
|
SELECT country_iso_code, country_name, city_name,time_zone
|
|
FROM (
|
|
SELECT *
|
|
FROM geolite2_city_ipv4_string
|
|
WHERE ? between network_start_ip and network_last_ip
|
|
LIMIT 1
|
|
) net
|
|
LEFT JOIN geolite2_city_locations_en ON net.geoname_id = geolite2_city_locations_en.geoname_id;
|
|
`
|
|
rows, err := db.Query(query, ip)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer rows.Close()
|
|
var IpInformatin IpInformation
|
|
// 处理查询结果
|
|
for rows.Next() {
|
|
var (
|
|
country_iso_code string
|
|
country_name string
|
|
city_name string
|
|
time_zone string
|
|
)
|
|
err := rows.Scan(&country_iso_code, &country_name, &city_name, &time_zone)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
IpInformatin = IpInformation{
|
|
Ip: ip,
|
|
CountryIsoCode: country_iso_code,
|
|
CountryName: country_name,
|
|
City: city_name,
|
|
TimeZone: time_zone,
|
|
}
|
|
// 打印结果
|
|
//fmt.Println("country_iso_code=", country_iso_code)
|
|
//fmt.Println("country_name=", country_name)
|
|
//fmt.Println("city_name=", city_name)
|
|
//fmt.Println("time_zone=", time_zone)
|
|
}
|
|
// 检查是否有错误发生
|
|
err = rows.Err()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
log.Print("tag:mysqlquery=", IpInformatin)
|
|
return IpInformatin
|
|
}
|