go 使用騰訊地圖定位ip的location

  • 事前準備
    • 申請騰訊位置服務開發者賬號 https://lbs.qq.com/dev/console/application/mine
    • 新建key 新增webservice 服務 。 選擇簽名校驗。 咱們這裏使用簽名的形式進行校驗。
    • 獲取到key 和祕鑰
  • 使用代碼獲取定位服務
    package commonlib
    
    import (
        "context"
        "crypto/md5"
        "encoding/hex"
        "fmt"
        heimdall "github.com/gojek/heimdall/v7/httpclient"
        json "github.com/json-iterator/go"
        "io/ioutil"
        "ipin-service/kratos/pkg/log"
        "ipin-service/library/tool"
        "time"
    )
    
    type Location struct {
        Lat float64 `json:"lat"`
        Lng float64 `json:"lng"`
    }
    
    type AdInfo struct {
        Nation   string `json:"nation"`
        Province string `json:"province"`
        City     string `json:"city"`
        District string `json:"district"`
        Adcode   int32  `json:"adcode"`
    }
    
    type LocationInfo struct {
        Ip       string   `json:"ip"`
        Location *Location `json:"location"`
        AdInfo   *AdInfo   `json:"ad_info"`
    }
    
    type LocationResponse struct {
        Status  int32        `json:"status"`
        Message string       `json:"message"`
        Result  *LocationInfo `json:"result"`
    }
    
    func md5V(str string) string {
        h := md5.New()
        h.Write([]byte(str))
        return hex.EncodeToString(h.Sum(nil))
    }
    
    //GetSin 
    func GetSin(urlPath, secret string) string {
        return md5V(urlPath + secret)
    }
    func GetLocationUrl(host, ip, key, secret string) string {
        urlPath := fmt.Sprintf("/ws/location/v1/ip?ip=%s&key=%s", ip, key)
        sin := GetSin(urlPath, secret)
        return fmt.Sprintf("%s%s&sig=%s", host, urlPath, sin)
    }
    
    func GetLocation(ctx context.Context, url string) (resp *LocationResponse, err error) {
        locationRsp := new(LocationResponse)
        // Create a new HTTP client with a default timeout
        timeout := 3 * time.Second
        client := heimdall.NewClient(heimdall.WithHTTPTimeout(timeout))
        startTime := tool.GetTimestampMS()
        // Use the clients GET method to create and execute the request
        res, err := client.Get(url, nil)
        endTime := tool.GetTimestampMS()
        log.Info("----------- call  academy interface [%v] cost [%v] ms ----------", url, endTime-startTime)
        if err != nil {
            return
        }
        // Heimdall returns the standard *http.Response object
        body, err := ioutil.ReadAll(res.Body)
        err = json.Unmarshal(body, locationRsp)
        if err != nil {
            return
        }
        resp = locationRsp
        return
    }

     

  • 使用示例
    func TestHttpClient(t *testing.T) {
        url := commonlib.GetLocationUrl("https://apis.map.qq.com", "111.206.145.41", "key", "secret")
        rsp, err := commonlib.GetLocation(context.Background(), url)
        if err != nil {
    
        }
        fmt.Sprintf("%v", rsp)
    }

    最後其他什麼

    //如果是部署在k8s 才能用這個方法  否則用 value.RemoteIP()
        ip := value.Request.Header.Get("X-Original-Forwarded-For")
        if tool.IsNullOrEmpty(ip) {
            ip = value.RemoteIP()
        }
    // RemoteIP implements a best effort algorithm to return the real client IP, it parses
    // X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
    // Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
    // Notice: metadata.RemoteIP take precedence over X-Forwarded-For and X-Real-Ip
    func (c *Context) RemoteIP() (remoteIP string) {
        //remoteIP = metadata.String(c, metadata.RemoteIP)
        //if remoteIP != "" {
        //    return
        //}
        remoteIP = c.Request.Header.Get("X-Forwarded-For")
        remoteIP = strings.TrimSpace(strings.Split(remoteIP, ",")[0])
        if remoteIP == "" {
            remoteIP = strings.TrimSpace(c.Request.Header.Get("X-Real-Ip"))
        }
        if remoteIP == "" {
            remoteIP = strings.TrimSpace(c.Request.Header.Get("RemoteIp"))
        }
        return
    }

     

    發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章