From c7df49ca8e56e3d516b1878f660ed4c2a7f014ed Mon Sep 17 00:00:00 2001 From: sjlleo Date: Tue, 24 May 2022 09:05:56 +0800 Subject: [PATCH] improve: #4 case insensitive --- go.sum | 2 ++ ipgeo/ipgeo.go | 8 +++++--- ipgeo/ipsb.go | 18 +++++++++++------- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/go.sum b/go.sum index 4e9638a..b74a7b3 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,6 @@ github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= @@ -53,4 +54,5 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/ipgeo/ipgeo.go b/ipgeo/ipgeo.go index f9762a8..0de5b71 100644 --- a/ipgeo/ipgeo.go +++ b/ipgeo/ipgeo.go @@ -1,5 +1,7 @@ package ipgeo +import "strings" + type IPGeoData struct { Asnumber string Country string @@ -13,12 +15,12 @@ type IPGeoData struct { type Source = func(ip string) (*IPGeoData, error) func GetSource(s string) Source { - switch s { - case "LeoMoeAPI": + switch strings.ToUpper(s) { + case "LEOMOEAPI": return LeoIP case "IP.SB": return IPSB - case "IPInsight": + case "IPINSIGHT": return IPInSight default: return nil diff --git a/ipgeo/ipsb.go b/ipgeo/ipsb.go index 46bdad1..8bee301 100644 --- a/ipgeo/ipsb.go +++ b/ipgeo/ipsb.go @@ -3,21 +3,25 @@ package ipgeo import ( "io/ioutil" "net/http" + "time" "github.com/tidwall/gjson" ) func IPSB(ip string) (*IPGeoData, error) { - resp, err := http.Get("https://api.ip.sb/geoip/" + ip) + url := "https://api.ip.sb/geoip/" + ip + client := &http.Client{ + // 2秒超时 + Timeout: 2 * time.Second, + } + req, _ := http.NewRequest("GET", url, nil) + // 设置 UA,ip.sb 默认禁止 go-client User-Agent 的 api 请求 + req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0") + content, err := client.Do(req) if err != nil { return nil, err } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - + body, _ := ioutil.ReadAll(content.Body) res := gjson.ParseBytes(body) return &IPGeoData{