check_ip/main.go

65 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"checkIP/modules"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"strings"
)
func getIPInfoAndRespond(w http.ResponseWriter, r *http.Request) {
// 获取访问者IP地址
ip := ""
xffHeader := r.Header.Get("X-Forwarded-For")
if xffHeader != "" {
// 如果X-Forwarded-For头部不为空则使用其中的第一个IP地址
ip = strings.Split(xffHeader, ", ")[0]
} else {
// 否则使用RemoteAddr提取IP地址可能包含端口信息
ip = strings.Split(r.RemoteAddr, ":")[0]
}
// 检查IP地址是否为空
if ip == "" {
w.Write([]byte("Invalid IP"))
return
}
// 获取IP信息
IPinfo := modules.GetIPInformation(ip)
if IPinfo.IsPrivate != false {
log.Println("tag:main", "IP: "+IPinfo.IP+", IsPrivate: "+strconv.FormatBool(IPinfo.IsPrivate)+", PrivateCIDR: "+IPinfo.PrivateCIDR)
} else {
log.Println("tag:main", "IP: "+IPinfo.IP+", IsPrivate: "+strconv.FormatBool(IPinfo.IsPrivate))
}
// 检查是否为私有IP
if IPinfo.IsPrivate == true {
w.Write([]byte("Invalid IP"))
return
}
// 使用mmdb查询ip
IpIformation := modules.MmdbQueryIP(IPinfo.IP)
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)
}