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")
	addressType := ""
	ipDomain := ""
	domain := ""
	switch {
	case address == "":
		//没传address值 则拿请求ip来查询
		addressReq, _ := util.GetIP(req)
		address = addressReq
		addressType = "self"
	case util.MatchIP(address):
		//传了address值  是ip 则直接查询
		addressType = "ip"
	default:
		//传了address值  不是ip 则查询ip
		ipAddress, err := util.GetIPByDomain(address)
		if err != nil {
			//提供非法域名 则拿请求ip来查询
			addressReq, _ := util.GetIP(req)
			address = addressReq
			addressType = "self"
		} else {
			//提供正确域名 则查询ip
			domain = address
			ipDomain = ipAddress
			address = ipAddress
			addressType = "domain"
		}
	}
	var ipInfo ip2region.IpInfo
	ipInfo, _ = ip2region.GetIPInfo(address, global.SearchType)
	switch addressType {
	case "ip":
		ipInfo.IP = address
		ipInfo.Domain = ""
	case "domain":
		ipInfo.IP = ipDomain
		ipInfo.Domain = domain
	case "self":
		ipInfo.IP = address
		ipInfo.Domain = ""
	}

	res, _ := json.Marshal(ipInfo)
	fmt.Fprintln(w, string(res))

}
