更新 main.go

master
wangsiyuan 2023-08-03 00:21:48 +08:00
parent 71bb4a4778
commit 268e4b044d
1 changed files with 50 additions and 42 deletions

92
main.go
View File

@ -4,53 +4,61 @@ import (
"checkIP/modules" "checkIP/modules"
"encoding/json" "encoding/json"
"fmt" "fmt"
_ "github.com/go-sql-driver/mysql"
"log" "log"
"net/http" "net/http"
"strings" "strings"
) )
func main() { func getIPInfoAndRespond(w http.ResponseWriter, r *http.Request) {
//modules.ImportDatabaseToHex() // 获取访问者IP地址
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { ip := ""
//测试用ip地址 xffHeader := r.Header.Get("X-Forwarded-For")
//ip := "192.168.2.134" if xffHeader != "" {
//获取访问浏览器ip // 如果X-Forwarded-For头部不为空则使用其中的第一个IP地址
ip := strings.Split(r.RemoteAddr, ":")[0] ip = strings.Split(xffHeader, ", ")[0]
//fmt.Println("客户端IP地址:", ip) } else {
if ip == "" { // 否则使用RemoteAddr提取IP地址可能包含端口信息
w.Write([]byte("Invalid IP")) ip = strings.Split(r.RemoteAddr, ":")[0]
return }
}
if ip != "" {
IPinfo := modules.GetIPInformation(ip)
fmt.Println("IP", IPinfo.IP)
fmt.Println("IsPrivate", IPinfo.IsPrivate)
fmt.Println("PrivateCIDR", IPinfo.PrivateCIDR)
if IPinfo.IsPrivate == true {
w.Write([]byte("Invalid IP"))
return
}
if IPinfo.IsPrivate != true {
//使用mmdb查询ip
IpIformation := modules.MmdbQueryIP(IPinfo.IP)
//使用MySql查询ip
//dsn := modules.Readconfig()
//IpIformation := modules.MysqlQuery(ip, dsn)
log.Println("tag:main", IpIformation) // 检查IP地址是否为空
jsonData, err := json.Marshal(IpIformation) if ip == "" {
if err != nil { w.Write([]byte("Invalid IP"))
fmt.Println("JSON 序列化失败:", err) return
return }
}
// 设置响应的 Content-Type 为 application/json // 获取IP信息
w.Header().Set("Content-Type", "application/json") IPinfo := modules.GetIPInformation(ip)
// 返回 JSON 数据 fmt.Println("IP", IPinfo.IP)
//log.Println(jsonData) fmt.Println("IsPrivate", IPinfo.IsPrivate)
w.Write(jsonData) fmt.Println("PrivateCIDR", IPinfo.PrivateCIDR)
}
} // 检查是否为私有IP
}) if IPinfo.IsPrivate == true {
w.Write([]byte("Invalid IP"))
return
}
// 使用mmdb查询ip
IpIformation := modules.MmdbQueryIP(IPinfo.IP)
// 使用MySql查询ip
//dsn := modules.Readconfig()
//IpIformation := modules.MysqlQuery(ip, dsn)
log.Println("tag:main", IpIformation)
jsonData, err := json.Marshal(IpIformation)
if err != nil {
fmt.Println("JSON 序列化失败:", err)
return
}
// 设置响应的 Content-Type 为 application/json
w.Header().Set("Content-Type", "application/json")
// 返回 JSON 数据
w.Write(jsonData)
}
func main() {
http.HandleFunc("/", getIPInfoAndRespond)
http.ListenAndServe(":8341", nil) http.ListenAndServe(":8341", nil)
} }