您的位置:首页 > 编程语言 > Go语言

go 通过淘宝api,查询出口ip详细信息

2017-01-10 14:24 555 查看
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"
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: