You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
1.3 KiB
64 lines
1.3 KiB
package main
|
|
|
|
import (
|
|
"IPRegion/global"
|
|
"IPRegion/ip2region"
|
|
"IPRegion/util"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
func main() {
|
|
http.HandleFunc("/", IPHandle)
|
|
log.Println("server start!")
|
|
http.ListenAndServe(":8080", nil)
|
|
}
|
|
|
|
func IPHandle(w http.ResponseWriter, req *http.Request) {
|
|
address := req.FormValue("address")
|
|
ipDomain := ""
|
|
domain := ""
|
|
ipInfoIP := ""
|
|
ipInfoDomain := ""
|
|
switch {
|
|
case address == "":
|
|
//没传address值 则拿请求ip来查询
|
|
addressReq, _ := util.GetIP(req)
|
|
address = addressReq
|
|
ipInfoIP = address
|
|
ipInfoDomain = ""
|
|
case util.MatchIP(address):
|
|
//传了address值 是ip 则直接查询
|
|
ipInfoIP = address
|
|
ipInfoDomain = ""
|
|
default:
|
|
//传了address值 不是ip 则查询ip
|
|
ipAddress, err := util.GetIPByDomain(address)
|
|
if err != nil {
|
|
//提供非法域名 则拿请求ip来查询
|
|
addressReq, _ := util.GetIP(req)
|
|
address = addressReq
|
|
ipInfoIP = address
|
|
ipInfoDomain = ""
|
|
} else {
|
|
//提供正确域名 则查询ip
|
|
domain = address
|
|
ipDomain = ipAddress
|
|
address = ipAddress
|
|
ipInfoIP = ipDomain
|
|
ipInfoDomain = domain
|
|
|
|
}
|
|
}
|
|
var ipInfo ip2region.IpInfo
|
|
ipInfo, _ = ip2region.GetIPInfo(address, global.SearchType)
|
|
ipInfo.IP = ipInfoIP
|
|
ipInfo.Domain = ipInfoDomain
|
|
|
|
res, _ := json.Marshal(ipInfo)
|
|
fmt.Fprintln(w, string(res))
|
|
|
|
}
|