我想通过我的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)}
任何帮助将不胜感激!
感谢数据float64。我会尝试这两件事。 –
为什么http://stackoverflow.com/a/31129967建议跳过'ioutil.ReadAll'并立即使用'Decode'? –
好吧,我修改了结构后有大写字段。在解析它之前,我不必阅读主体。我保持原样。现在它工作了!谢谢! –