github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/goip/info.go (about)

     1  package goip
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  	"time"
    10  )
    11  
    12  // https://topic.alibabacloud.com/a/go-combat-golang-get-public-ip-view-intranet-ip-detect-ip-type-verify-ip-range-ip-address-string-and-int-conversion-judge-by-ip_1_38_10267608.html
    13  
    14  // Info ...
    15  type Info struct {
    16  	Code int `json:"code"`
    17  	Data IP  `json:"data"`
    18  }
    19  
    20  // IP ...
    21  type IP struct {
    22  	Country   string `json:"country"`
    23  	CountryID string `json:"country_id"`
    24  	Area      string `json:"area"`
    25  	AreaID    string `json:"area_id"`
    26  	Region    string `json:"region"`
    27  	RegionID  string `json:"region_id"`
    28  	City      string `json:"city"`
    29  	CityID    string `json:"city_id"`
    30  	Isp       string `json:"isp"`
    31  }
    32  
    33  // TabaoAPI ...
    34  func TabaoAPI(ip string) (*Info, error) {
    35  	ctx, cncl := context.WithTimeout(context.Background(), time.Second*10)
    36  	defer cncl()
    37  
    38  	addr := "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip
    39  	resp, err := http.NewRequestWithContext(ctx, http.MethodGet, addr, nil)
    40  	if err != nil {
    41  		return nil, fmt.Errorf("failed http.Get(%s), × err: %w", addr, err)
    42  	}
    43  
    44  	defer resp.Body.Close()
    45  
    46  	out, err := ioutil.ReadAll(resp.Body)
    47  	if err != nil {
    48  		return nil, fmt.Errorf("failed ioutil.ReadAll, × err: %w", err)
    49  	}
    50  
    51  	var result Info
    52  
    53  	if err := json.Unmarshal(out, &result); err != nil {
    54  		return nil, fmt.Errorf("failed json.Unmarshal %s, × err: %w", string(out), err)
    55  	}
    56  
    57  	return &result, nil
    58  }