有時(shí)候我們可能需要根據(jù)用戶IP判斷請(qǐng)求是否允許,可以用iplocation的免費(fèi)公開接口來(lái)完成
可以使用下面這個(gè)封裝庫(kù)快速請(qǐng)求查詢IP的所屬信息
go get -u github.com/skys-mission/gout/go/pubnet/iplocation
示例代碼
package main
import (
"context"
"fmt"
"time"
"github.com/skys-mission/gout/go/pubnet/iplocation"
)
func main() {
ctx, cf := context.WithTimeout(context.Background(), time.Second)
defer cf()
result, err := iplocation.RequestIPLocator(ctx, "8.8.8.8")
if err != nil {
panic(err)
}
if result.ResponseCode != iplocation.ResponseCodeOKForIPLocator {
panic(fmt.Errorf("code: %v msg: %v", result.ResponseCode, result.ResponseMessage))
}
fmt.Printf("%+v\ntype: %T", result, result)
}
輸出樣例
&{IP:8.8.8.8 IPNumber:134744072 IPVersion:4 CountryName:United States of America CountryCode2:US ISP:Google LLC ResponseCode:200 ResponseMessage:OK}
type: *iplocation.IPLocatorResp
Process finished with the exit code 0
查詢語(yǔ)言代碼
返回參數(shù)CountryCode2用的是ISO 3166-1 Alpha-2標(biāo)準(zhǔn),可以用這個(gè)庫(kù)的常量判斷是否是那個(gè)地區(qū)
# Alpha-2指的是兩位代碼,很多國(guó)家也被劃分成多個(gè)代碼用來(lái)標(biāo)識(shí)IP來(lái)源
iplocation.LocalCodeChinaMainland # CN
iplocation.LocalCodeChinaTaiwan # TW
iplocation.LocalCodeChinaHongKong # HK
iplocation.LocalCodeChinaMacao # MO
iplocation.LocalCodeUS # US
...等
- 標(biāo)準(zhǔn):ISO 3166-1 alpha-2 - Wikipedia
- 代碼倉(cāng)庫(kù)其實(shí)給的不全,但一般夠用了,比如判斷符不符合AI服務(wù)要求:gout庫(kù)中的地區(qū)代碼常量
注意事項(xiàng)
- 你應(yīng)該使用go mod
- go version >=1.18
- 你不應(yīng)該頻繁地調(diào)用免費(fèi)接口,你可以使用緩存把結(jié)果緩存一段時(shí)間
如果你不想使用>=1.18的庫(kù)可以參考庫(kù)的實(shí)現(xiàn)
開源地址:gout