package main
import (
"encoding/json"
"errors"
"io/ioutil"
"net"
"net/http"
"strings"
log "qiniupkg.com/x/log.v7"
"time"
"fmt"
"github.com/gin-gonic/gin"
"mars.qiniu.com/collections"
"mars.qiniu.com/models"
)
// TaoBaoAPI to get the taobao api
func TaoBaoAPI(ip string, ipj *models.IPJson) (err error) {
fmt.Printf(ip)
client := &http.Client{}
request, _ := http.NewRequest("GET", "http://ip.taobao.com/service/getIpInfo.php?ip="+ip, nil)
resp, err := client.Do(request)
if err != nil {
return
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
fmt.Printf(string(data[:]))
return json.Unmarshal(data, ipj)
}
//IPGet is to get the ip by ip info
func IPGet(c *gin.Context) {
j := &models.IPJson{}
ip, err := collections.IPMgr.Find(&models.IP{IP: ClientIP(c)})
if err != nil {
if err.Error() == "not found" {
if err := TaoBaoAPI(ClientIP(c), j); err != nil {
log.Error(err.Error())
c.JSON(404, err)
c.Abort()
return
}
if j.Code == 1 {
log.Error(errors.New("taobao not found"))
c.JSON(404, err)
c.Abort()
return
}
if err := collections.IPMgr.Upsert(&j.Data); err != nil {
log.Error(err.Error())
c.JSON(500, err)
c.Abort()
return
}
c.JSON(200, j.Data)
return
}
log.Error(err.Error())
c.JSON(404, err)
c.Abort()
return
}
if (time.Now().Day() - ip.UpdatedAt.Day()) > 20 {
if err := TaoBaoAPI(ClientIP(c), j); err != nil {
log.Error(err.Error())
} else {
if j.Code == 1 {
log.Error(errors.New("taobao not found"))
} else {
if err := collections.IPMgr.Upsert(&j.Data); err != nil {
log.Error(err.Error())
} else {
c.JSON(200, j.Data)
return
}
}
}
}
c.JSON(200, ip)
}
//ClientIP is to get remote ip
func ClientIP(c *gin.Context) string {
clientIP := c.Request.Header.Get("X-Forwarded-For")
if index := strings.IndexByte(clientIP, ','); index >= 0 {
clientIP = clientIP[0:index]
}
clientIP = strings.TrimSpace(clientIP)
if len(clientIP) > 0 {
return clientIP
}
clientIP = strings.TrimSpace(c.Request.Header.Get("X-Real-Ip"))
if len(clientIP) > 0 {
c.JSON(200, gin.H{"ip": clientIP})
return clientIP
}
if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
return ip
}
return "127.0.0.1"
}
go 通过淘宝api,查询出口ip详细信息
最新推荐文章于 2023-07-13 17:29:03 发布