使用geoIP資料庫解析IP到城市jsonRPC服務教程

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。### RESTful介面**請求URL:** - ` https://api.turboes.com/Tbsapi/v1/ip2addr?ip=219.140.227.235` **請求方式:**- GET **參數:** |參數名|類型|說明||:----- |:-----|----- ||ip |url-qurey-string | `可選` 要查詢的ip地址,如果不傳這表示當前的ip | **返回樣本**``` { "code": 1, "data": { "Country": "中國", "Province": "湖北省", "City": "武漢", "ISP": "", "Latitude": 30.5801, "Longitude": 114.2734, "TimeZone": "Asia/Shanghai" }, "ip": "219.140.227.235"}```> json_rpc `tcp` 地址: `121.40.238.123`(IP地址更快) `api.turboes.com` 連接埠: `3344`***### 第三方資源* [GeoIP2 Reader for Go](https://github.com/oschwald/geoip2-golang)* [GeoLite2 開來源資料庫](https://dev.maxmind.com/zh-hans/geoip/geoip2/geolite2-%E5%BC%80%E6%BA%90%E6%95%B0%E6%8D%AE%E5%BA%93/)### go標準庫jsonRPC服務端> Go官方提供了一個RPC庫: net/rpc。包rpc提供了通過網路訪問一個對象的方法的能力。伺服器需要註冊對象, 通過對象的類型名暴露這個服務。註冊後這個對象的輸出方法就可以遠程調用,這個庫封裝了底層傳輸的細節,包括序列化。伺服器可以註冊多個不同類型的對象,但是註冊相同類型的多個對象的時候回出錯。> * 方法的類型是可輸出的 (the method's type is exported)> * 方法本身也是可輸出的 (the method is exported)> * 方法必須由兩個參數,必須是輸出類型或者是內建類型 (the method has two arguments, both exported or builtin types)> * 方法的第二個參數是指標類型 (the method's second argument is a pointer)> * 方法傳回型別為 error (the method has return type error)```gopackage mainimport ("fmt""github.com/oschwald/geoip2-golang""net""net/rpc""net/rpc/jsonrpc""os""log")//傳回值結構體//需要滿足以上要求type Response struct {Country stringProvince stringCity stringISP stringLatitude float64Longitude float64TimeZone string}type Ip2addr struct {db *geoip2.Reader}//參數結構體//需要滿足以上要求type Agrs struct {IpString string}//json rpc 處理請求//需要滿足以上要求func (t *Ip2addr) Address(agr *Agrs, res *Response) error {netIp := net.ParseIP(agr.IpString) //調用開源geoIp 資料庫查詢ip地址record, err := t.db.City(netIp)res.City = record.City.Names["zh-CN"]res.Province = record.Subdivisions[0].Names["zh-CN"]res.Country = record.Country.Names["zh-CN"]res.Latitude = record.Location.Latituderes.Longitude = record.Location.Longituderes.TimeZone = record.Location.TimeZonereturn err}func main() { //載入geoIp資料庫db, err := geoip2.Open("./GeoLite2-City.mmdb")if err != nil {log.Fatal(err)} //初始化jsonRPCip2addr := &Ip2addr{db} //註冊rpc.Register(ip2addr) //綁定連接埠address := ":3344"tcpAddr, err := net.ResolveTCPAddr("tcp", address)checkError(err)listener, err := net.ListenTCP("tcp", tcpAddr)checkError(err)log.Println("json rpc is listening",tcpAddr)for {conn, err := listener.Accept()if err != nil {continue}jsonrpc.ServeConn(conn)}}func checkError(err error) {if err != nil {fmt.Println("Fatal error ", err.Error())os.Exit(1)}}```### PHP-jsonRPC用戶端```goclass JsonRPC{ public $conn; function __construct($host, $port) { $this->conn = fsockopen($host, $port, $errno, $errstr, 3); if (!$this->conn) { return false; } } public function Call($method, $params) { $obj = new stdClass(); $obj->code = 0; if (!$this->conn) { $obj->info = "jsonRPC串連失敗!請聯絡qzhou@turboes.com"; return $obj; } $err = fwrite($this->conn, json_encode(array( 'method' => $method, 'params' => array($params), 'id' => 0, )) . "\n"); if ($err === false) { fclose($this->conn); $obj->info = "jsonRPC發送參數失敗!請檢查自己的rpc-client代碼"; return $obj; } stream_set_timeout($this->conn, 0, 3000); $line = fgets($this->conn); fclose($this->conn); if ($line === false) { $obj->info = "jsonRPC返回訊息為空白!請檢查自己的rpc-client代碼"; return $obj; } $temp = json_decode($line); $obj->code = $temp->error == null ? 1 : 0; $obj->data = $temp->result; return $obj; }}function json_rpc_ip_address($ipString){ $client = new JsonRPC("127.0.0.1", 3344); $obj = $client->Call("Ip2addr.Address", ['IpString' => $ipString]); return $obj;}```### go語言jsonRPC用戶端```gopackage mainimport ("fmt""log""net/rpc/jsonrpc")type Response struct {Country stringProvince stringCity stringISP stringLatitude float64Longitude float64TimeZone string}type Agrs struct {IpString string}func main() {client, err := jsonrpc.Dial("tcp", "121.40.238.123:3344")if err != nil {log.Fatal("dialing:", err)}// Synchronous callvar res Responseerr = client.Call("Ip2addr.Address", Agrs{"219.140.227.235"}, &res)if err != nil {log.Fatal("ip2addr error:", err)}fmt.Println(res)}```### [代碼地址](https://github.com/mojocn/ip2location/tree/master/example)### [歡迎pr/star golang-captcha](https://github.com/mojocn/base64Captcha)306 次點擊  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.