From 9f9f04fabbd32c393438aad8e3ecff3b6b2dcb3f Mon Sep 17 00:00:00 2001 From: zenghongru Date: Fri, 14 Aug 2020 20:01:58 +0800 Subject: [PATCH] feat: ip location --- api.go | 1 + district.go | 8 +------- ip_location.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ meta.go | 12 ++++++++++++ 4 files changed, 60 insertions(+), 7 deletions(-) create mode 100644 ip_location.go create mode 100644 meta.go diff --git a/api.go b/api.go index fe1b997..1d43ecf 100644 --- a/api.go +++ b/api.go @@ -13,6 +13,7 @@ const ( districtList API = "/ws/district/v1/list" districtGetChildren API = "/ws/district/v1/getchildren" districtSearch API = "/ws/district/v1/search" + ipLocation API = "/ws/location/v1/ip" ) // Full returns the full path. diff --git a/district.go b/district.go index e4bace6..fcb9ea3 100644 --- a/district.go +++ b/district.go @@ -7,17 +7,11 @@ import ( // DistrictResponse 行政区划回复 type DistrictResponse struct { - Status int `json:"status"` - Message string `json:"message"` + Meta DataVersion string `json:"data_version"` Result [][]*DistrictInfo `json:"result"` } -// Success means a valid response. -func (r *DistrictResponse) Success() bool { - return r != nil && r.Status == 0 -} - // DistrictInfo 行政区划信息 type DistrictInfo struct { ID string `json:"id"` diff --git a/ip_location.go b/ip_location.go new file mode 100644 index 0000000..0134b89 --- /dev/null +++ b/ip_location.go @@ -0,0 +1,46 @@ +package txlbs + +import ( + "context" + "net/url" +) + +// IPLocationResponse IP定位回复 +type IPLocationResponse struct { + Meta + Result struct { + IP string `json:"ip"` + Location struct { + Lng float64 `json:"lng"` + Lat float64 `json:"lat"` + } `json:"location"` + AdInfo struct { + Nation string `json:"nation"` + Province string `json:"province"` + City string `json:"city"` + Adcode int `json:"adcode"` + } `json:"ad_info"` + } `json:"result"` +} + +// IPLocation 定位查询 +func (c *Client) IPLocation(ctx context.Context, ip string) (*IPLocationResponse, error) { + v := url.Values{} + if ip != "" { + v.Set("ip", ip) + } + v, err := c.signatureQueryParameter(v, string(ipLocation)) + if err != nil { + return nil, err + } + r := c.ca.NewRequest().WithPath(ipLocation.Full(v.Encode())) + resp, err := c.ca.Do(ctx, r) + if err != nil { + return nil, err + } + var dr IPLocationResponse + if err := resp.DecodeFromJSON(&dr); err != nil { + return nil, err + } + return &dr, nil +} diff --git a/meta.go b/meta.go new file mode 100644 index 0000000..e2e2bc1 --- /dev/null +++ b/meta.go @@ -0,0 +1,12 @@ +package txlbs + +// Meta includes common response info. +type Meta struct { + Status int `json:"status"` + Message string `json:"message"` +} + +// Success means a valid response. +func (r *Meta) Success() bool { + return r != nil && r.Status == 0 +}