IP 地址归属地查询 API
最近小小学习了一下Go,就尝试写了个查询 IPv4 地址归属地的 api,已经上传到github供大家参考学习。
github仓库链接:WHQ12520/Go_IP_home_address_api
main.go源代码
(这次就懒得写注释了💦💦💦)
package main
import (
"fmt"
"net/http"
"os"
"text/template"
"time"
"github.com/thinkeridea/go-extend/exnet"
"github.com/xiaoqidun/qqwry"
)
func main() {
var listen_addr string
if len(os.Args) > 1 && os.Args[1] != "" {
listen_addr = os.Args[1]
} else {
listen_addr = "0.0.0.0:12520"
}
var ipdate string
if len(os.Args) > 2 && os.Args[2] != "" {
ipdate = os.Args[2]
} else {
ipdate = "./ipdata/qqwry.dat"
}
// 从文件加载IP数据库
if err := qqwry.LoadFile(ipdate); err != nil {
fmt.Println("Error: ", ipdate, "地址数据库加载失败")
panic(err)
}
http.HandleFunc("/", web_http_client)
fmt.Println("INFO:监听地址", listen_addr)
http.ListenAndServe(listen_addr, nil)
}
func web_http_client(w http.ResponseWriter, r *http.Request) {
ip := r.URL.Query().Get("ip")
if ip == "" {
ip = exnet.ClientPublicIP(r)
}
ip_data, _ := qqwry.QueryIP(ip)
fmt.Println(
nowtime(),
"IP:", ip_data.IP,
"地区:", ip_data.Country,
"省份:", ip_data.Province,
"城市:", ip_data.City,
"区县:", ip_data.District,
"运营商:", ip_data.ISP,
)
t, err := template.ParseFiles("./index.html")
if err != nil {
http.Error(w, "500 内部服务器错误", http.StatusInternalServerError)
fmt.Println("Error:模版解析失败 ", err)
return
}
data := map[string]string{
"ip": ip_data.IP,
"Country": ip_data.Country,
"Province": ip_data.Province,
"City": ip_data.City,
"District": ip_data.District,
"ISP": ip_data.ISP,
}
err = t.Execute(w, data)
if err != nil {
http.Error(w, "500 内部服务器错误", http.StatusInternalServerError)
fmt.Println("Error:写入请求失败 ", err)
}
}
func nowtime() string {
timeStr := time.Now().Format("2006-01-02 15:04:05")
fmt.Println(timeStr)
return timeStr
}
IP 数据库
IP 数据库使用了 QQ 纯真数据库
使用前请下载 IP 数据库,放置到默认路径 ./ipdata/qqwry.dat
或者在参数中传入 IP 数据库路径
IP 数据库下载地址:https://github.com/nmgliangwei/qqwry (感谢数据库作者的辛勤维护~)
运行配置
默认监听地址:0.0.0.0:12520
默认数据库路径 ./ipdata/qqwry.dat
可以在第一个参数中配置监听地址
可以在第二个参数中传入 IP 数据库路径
例子:./Go_IP_home_address_api 0.0.0.0:1000 ./qqwry.dat
调用方法
方法1:请求不带参数,返回 API 调用者的 IP 地址和 IP 对应归属地
方法2:请求携带参数,返回参数中的 IP 地址和 IP 对应归属地
示例
不带参数的请求:
curl http://localhost:12520/
带参数的请求:
curl http://localhost:12520/?ip=1.1.1.1
依赖
在以源代码运行前请确保安装这些依赖:
go get github.com/thinkeridea/go-extend/exnet
go get github.com/xiaoqidun/qqwry