更新 main.go
parent
71bb4a4778
commit
268e4b044d
36
main.go
36
main.go
|
|
@ -4,34 +4,41 @@ 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 {
|
||||||
|
// 否则,使用RemoteAddr提取IP地址(可能包含端口信息)
|
||||||
|
ip = strings.Split(r.RemoteAddr, ":")[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查IP地址是否为空
|
||||||
if ip == "" {
|
if ip == "" {
|
||||||
w.Write([]byte("Invalid IP"))
|
w.Write([]byte("Invalid IP"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if ip != "" {
|
|
||||||
|
// 获取IP信息
|
||||||
IPinfo := modules.GetIPInformation(ip)
|
IPinfo := modules.GetIPInformation(ip)
|
||||||
fmt.Println("IP", IPinfo.IP)
|
fmt.Println("IP", IPinfo.IP)
|
||||||
fmt.Println("IsPrivate", IPinfo.IsPrivate)
|
fmt.Println("IsPrivate", IPinfo.IsPrivate)
|
||||||
fmt.Println("PrivateCIDR", IPinfo.PrivateCIDR)
|
fmt.Println("PrivateCIDR", IPinfo.PrivateCIDR)
|
||||||
|
|
||||||
|
// 检查是否为私有IP
|
||||||
if IPinfo.IsPrivate == true {
|
if IPinfo.IsPrivate == true {
|
||||||
w.Write([]byte("Invalid IP"))
|
w.Write([]byte("Invalid IP"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if IPinfo.IsPrivate != true {
|
|
||||||
// 使用mmdb查询ip
|
// 使用mmdb查询ip
|
||||||
IpIformation := modules.MmdbQueryIP(IPinfo.IP)
|
IpIformation := modules.MmdbQueryIP(IPinfo.IP)
|
||||||
// 使用MySql查询ip
|
// 使用MySql查询ip
|
||||||
|
|
@ -44,13 +51,14 @@ func main() {
|
||||||
fmt.Println("JSON 序列化失败:", err)
|
fmt.Println("JSON 序列化失败:", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置响应的 Content-Type 为 application/json
|
// 设置响应的 Content-Type 为 application/json
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
// 返回 JSON 数据
|
// 返回 JSON 数据
|
||||||
//log.Println(jsonData)
|
|
||||||
w.Write(jsonData)
|
w.Write(jsonData)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
})
|
func main() {
|
||||||
|
http.HandleFunc("/", getIPInfoAndRespond)
|
||||||
http.ListenAndServe(":8341", nil)
|
http.ListenAndServe(":8341", nil)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue