github.com/zooyer/miskit@v1.0.71/sdk/ips/ip.hzz.cool.go (about)

     1  package ips
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"github.com/zooyer/miskit/log"
     8  	"github.com/zooyer/miskit/zrpc"
     9  	url2 "net/url"
    10  	"time"
    11  )
    12  
    13  type Option struct {
    14  	Retry   int
    15  	Logger  *log.Logger
    16  	Timeout time.Duration
    17  }
    18  
    19  type Client struct {
    20  	url    string
    21  	option Option
    22  	client *zrpc.Client
    23  }
    24  
    25  type IP struct {
    26  	IP       string `json:"ip"`
    27  	Country  string `json:"country"`
    28  	Province string `json:"province"`
    29  	City     string `json:"city"`
    30  	County   string `json:"county"`
    31  	Region   string `json:"region"`
    32  	ISP      string `json:"isp"`
    33  }
    34  
    35  func New(option Option) *Client {
    36  	return &Client{
    37  		url:    "https://ip.hzz.cool",
    38  		option: option,
    39  		client: zrpc.New("ips", option.Retry, option.Timeout, option.Logger),
    40  	}
    41  }
    42  
    43  func (c *Client) QueryIP(ctx context.Context, ip string) (_ *IP, err error) {
    44  	var resp struct {
    45  		Code int    `json:"code"`
    46  		Msg  string `json:"msg"`
    47  		Data IP     `json:"data"`
    48  	}
    49  
    50  	var req = url2.Values{
    51  		"ip": {ip},
    52  	}
    53  
    54  	data, _, err := c.client.Get(ctx, c.url, req, nil)
    55  	if err != nil {
    56  		return
    57  	}
    58  
    59  	if err = json.Unmarshal(data, &resp); err != nil {
    60  		return
    61  	}
    62  
    63  	if resp.Code != 0 && resp.Code != 200 {
    64  		return nil, fmt.Errorf("query ip fail, code: %d, msg:%s", resp.Code, resp.Msg)
    65  	}
    66  
    67  	return &resp.Data, nil
    68  }