2016-06-21 46 views
0

我想通过我的IP地址使用http://ip-api.com/ api来获取经度和纬度。当我从浏览器或curl访问http://ip-api.com/json时,它会在json中返回正确的信息。但是当我尝试从我的程序中使用API​​时,API响应有一个空的主体(或者看起来好像)。试图查询一个API,但API响应是空的

我想在这个应用程序中做到这一点。该Ip_response_success结构是根据这里的API文档http://ip-api.com/docs/api:json

type Ip_response_success struct { 
    as   string 
    city  string 
    country  string 
    countryCode string 
    isp   string 
    lat   string 
    lon   string 
    org   string 
    query  string 
    region  string 
    regionName string 
    status  string 
    timezone string 
    zip   string 
} 

func Query(url string) (Ip_response_success, error) { 
    resp, err := http.Get(url) 
    if err != nil { 
     return Ip_response_success{}, err 
    } 
    fmt.Printf("%#v\n", resp) 

    var ip_response Ip_response_success 
    defer resp.Body.Close() 
    err = json.NewDecoder(resp.Body).Decode(&ip_response) 
    if err != nil { 
     return Ip_response_success{}, err 
    } 
    body, err := ioutil.ReadAll(resp.Body) 
    fmt.Printf("%#v\n", string(body)) 
    return ip_response, nil 
} 

func main() { 
    ip, err := Query("http://ip-api.com/json") 
    if err != nil { 
     fmt.Printf("%#v\n", err) 
    } 
} 

但最奇特的地方响应的正文为空做。它在响应中提供了200个状态码,所以我假设在API调用中没有错误。该API没有提及任何认证要求或用户代理要求,事实上,当我通过浏览器对其进行卷曲或访问时,似乎不需要任何特别的东西。有没有什么我在做我的程序错误或我使用API​​错误?

我尝试在代码内打印响应,但resp.body只是空白。来自http.Response结构的打印样本响应:

&http.Response{Status:"200 OK", StatusCode:200, Proto:"HTTP/1.1", ProtoMajor:1, 
ProtoMinor:1, Header:http.Header{"Access-Control-Allow-Origin":[]string{"*"}, 
"Content-Type":[]string{"application/json; charset=utf-8"}, "Date": 
[]string{"Tue, 21 Jun 2016 06:46:57 GMT"}, "Content-Length":[]string{"340"}}, 
Body:(*http.bodyEOFSignal)(0xc820010640), ContentLength:340, TransferEncoding: 
[]string(nil), Close:false, Trailer:http.Header(nil), Request:(*http.Request) 
(0xc8200c6000), TLS:(*tls.ConnectionState)(nil)} 

任何帮助将不胜感激!

回答

2

首先,你必须阅读的身体,然后分析它:

body, err := ioutil.ReadAll(resp.Body) 
err = json.NewDecoder(body).Decode(&ip_response) 
if err != nil { 
    return Ip_response_success{}, err 
} 

另外,在去了,JSON解码器必须能够访问到结构的领域。这意味着他们必须暴露在你的包装之外。

这意味着你使用JSON批注指定映射:

type Ip_response_success struct { 
    As   string `json: "as"` 
    City  string `json: "city"` 
    Country  string `json: "country"` 
    CountryCode string `json: "countryCode"` 
    Isp   string `json: "isp"` 
    Lat   float64 `json: "lat"` 
    Lon   float64 `json: "lon"` 
    Org   string `json: "org"` 
    Query  string `json: "query"` 
    Region  string `json: "region"` 
    RegionName string `json: "regionName"` 
    Status  string `json: "status"` 
    Timezone string `json: "timezone"` 
    Zip   string `json: "zip"` 
} 

还请注意,我改变了经度/纬度类型根据服务器发送

+0

感谢数据float64。我会尝试这两件事。 –

+0

为什么http://stackoverflow.com/a/31129967建议跳过'ioutil.ReadAll'并立即使用'Decode'? –

+0

好吧,我修改了结构后有大写字段。在解析它之前,我不必阅读主体。我保持原样。现在它工作了!谢谢! –